What is wrong with the in_array (...) PHP function?

The PHP function in_array(...)"checks if a value exists in an array."

But I am observing very strange behavior when processing strings (PHP v7.0.3). This code

$needle = 'a';
$haystacks = [['a'], ['b'], [123], [0]];
foreach ($haystacks as $haystack) {
    $needleIsInHaystack = in_array($needle, $haystack);
    var_dump($needleIsInHaystack);
}

generates the following result:

bool(true)
bool(false)
bool(false)
bool(true) <- WHAT?

The function returns truefor each string $needleif it $haystackcontains an element with a value 0!

Is it really by design? Or is it a mistake and should it be reported?

+4
source share
1 answer

If you do not set the third parameter in_arrayto true, the comparison is performed using type coercion.

strict TRUE, in_array() .

, 'a' 0 (int)'a' == 0.

+12

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


All Articles