jitendrapurohit jitendrapurohit - 11 months ago 52
PHP Question

array_search() returns 1 if $needle is 0

This is weird thing I found with


$test = array(
1 => 'first',
2 => 'second'

Now if the needle to be searched comes as 0 For eg:

$val = 0;
$key = array_search($val, $test);

is returned as
(the first key).

Does anyone know how to deal with such behaviour and return
for this check ? Is it documented anywhere ? I've searched but not found even on SO.


Answer Source

This is not a bug, but how PHP handles comparisons. As $val is an integer, PHP will convert your strings to integers for the comparison. Converting 'first' to an integer will give you 0, and so the comparison is 0 == 0, which is obviously true. That's why it returns the first result.