Array_search returns an invalid key

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 searched through the network and this is not an isolation problem. It appears that when the associative array contains the value 0, array_search fails if the strict parameter is not set.

There are also several error warnings, all rejected with motivation: "array_search () makes free comparison by default."

Ok, I solve my little problem using a strict parameter ...

But my question is: is there a decent, good reason why in the free comparison 'Mary'==0 or 'two'==0 , or is this just another php madness?

+6
source share
4 answers

You need to set the third parameter to true to use strict comparison. Please see below explanation:

array_search uses == to compare values ​​during a search

FORM PHP DOC

If the third strict parameter is set to TRUE, the array_search () function will look for identical elements in the haystack. This means that it also checks the types of needles in the haystack, and the objects must be of the same instance.

Beware of the second element 0 string was converted to 0 during search

Simple test

 var_dump("Mary" == 0); //true var_dump("Mary" === 0); //false 

The solution uses the strict parameter to search for identical values.

 $key = array_search("Mary", $ar,true); ^---- Strict Option var_dump($key); 

Output

 string(4) "key3" 
+8
source

You have a 0 (zero) numeric value in the array, and array_search() does non-line comparison (==) by default. 0 == 'Mary' true, you must pass the third parameter to array_search() (true).

+4
source

You just chnage in your array in 'key2'=>'0' you don't give a single or double quote

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

it works fine

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

All Articles