jitendrapurohit jitendrapurohit - 1 month ago 4
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);


Now
$key
is returned as
1
(the first key).

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

Thanks!

Answer

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.

Comments