This question already has an answer here:
- PHP in_array() / array_search() odd behaviour 2 answers
I recently noticed trouble when using the array_search function in my code. I am searching the array "$allcraftatts" for the value "sharp". I tried to isolate the problem by setting up a two line experiment:
$testcopy=$allcraftatts; $testsharp=array_search("sharp", $testcopy);
Using "print_r(get_defined_vars());" later on, I get this result:
[testcopy] => Array (  => 0  => 0  => 0  => 0  => 0  => 0  => Sharp Stone  => Sharp Stones  => stone  => object  => sharp  => hard  => 0  => 0  => 0  => 0  => 0  => 0  => 0 ) [testsharp] => 0
I made sure that I do not modify these variables at any other time.
Now, if I change my code to
$testcopy=$allcraftatts; unset($testcopy); $testsharp=array_search("sharp", $testcopy);
it returns "1".
This leads me to believe that it always returns the first key in the array.
It baffles me! This is one of those bugs that makes you fear something wrong with the language itself. However doubtful this is, I actually was eventually driven to looking at the PHP source for something wrong there, but unfortunately could not understand it.
Seeing that it is a function simple as this, I will most definitely be completely humiliated by the inevitably simple answer, but at this point, I just want an answer.
array_search is using
== to compare values during search
FORM PHP DOC
If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also check the types of the needle in the haystack, and objects must be the same instance.
Becasue the first element is
0 the string was converted to
0 during search
var_dump("sharp" == 0); //true var_dump("sharp" === 0); //false
strict option to search identical values
$testsharp = array_search("sharp", $testcopy,true); ^---- Strict Option var_dump($testsharp);