array_search返回错误的密钥[重复]

This question already has an answer here:

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?

</div>

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).

You just chnage in your array in 'key2'=>'0' you not give single or double quotation

$ar = [ 'key1'=>'John', 'key2'=>'0', 'key3'=>'Mary' ];

this is working fine

  $ar = [ 'key1'=>'John', 'key2'=>'0', 'key3'=>'Mary' ];