Can I use substr () as a needle in in_array ()?

$haystack = 'I am a haystack. Hear me rawr.';
$pos = strlen($haystack);
$nlen = 1;

$needle = array('.', '. ');

print_r(in_array(substr($haystack, $pos, $nlen), $needle, true));

It’s hard for me to understand why this fails. I'm trying to see if the needle array matches the result that substr selects from a haystack? How can I return this value as boolean?

+3
source share
1 answer

Yes and NO , because it substrreturns a string, which is the needle in your case and FALSE on failure, in which case it will not be a valid function argument in_array.

First you have to extract part of the string using substr, and you need to make sure that you have extracted some string, and it did not return FALSE, only then you should use it in in_array.

+3
source

Source: https://habr.com/ru/post/1759653/


All Articles