-2

This is weird thing I found with array_search();

$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!

jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39
  • 1
    And that's why `array_search` also has a `$strict` parameter… – deceze Oct 20 '16 at 12:46
  • Which one is well documented right here http://php.net/manual/de/function.array-search.php – Twinfriends Oct 20 '16 at 12:48
  • 1
    Duplicate: http://stackoverflow.com/q/2739441/3933332 (<- @deceze This might be a better duplicate for the "Odd array_search() behaviour" questions) – Rizier123 Oct 20 '16 at 12:59
  • didn't felt it was so straight - All I found was search a `text` inside an array, Thought there would be special handling for 0. But the answer by Styphon says it all. It was just the conversion happening. Thanks! – jitendrapurohit Oct 20 '16 at 13:07

1 Answers1

2

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.

Styphon
  • 10,304
  • 9
  • 52
  • 86