I have this array:
$ar = [ 'key1'=>'John', 'key2'=>0, 'key3'=>'Mary' ];
and, if I write:
$idx = array_search ('Mary',$ar);
echo $idx;
I get:
key2
I have searched over the net and this is not isolate problem. It seems that when an associative array contains a 0 value, array_search fails if strict parameter is not set.
There are also more than one bug warnings, all rejected with motivation: “array_search() does a loose comparison by default”.
Ok, I resolve my little problem using strict parameter...
But my question is: there is a decent, valid reason why in loose comparison 'Mary'==0
or 'two'==0
or it is only another php madness?
You need to set third parameter as true
to use strict comparison. Please have a look at below explanation:
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 second element is 0
the string was converted to 0
during search
Simple Test
var_dump("Mary" == 0); //true
var_dump("Mary" === 0); //false
Solution use strict
option to search identical values
$key = array_search("Mary", $ar,true);
^---- Strict Option
var_dump($key);
Output
string(4) "key3"
You have a 0 (zero) numeric value in array, and array_search()
perform non-strict comparison (==) by default. 0 == 'Mary'
is true, you should pass 3rd parameter to array_search()
(true).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With