php - array_search return wrong key -


this question has answer here:

i have array:

$ar = [ 'key1'=>'john', 'key2'=>0, 'key3'=>'mary' ]; 

and, if write:

$idx = array_search ('mary',$ar); echo $idx; 

i get:

key2 

i have searched on net , not isolate problem. seems when associative array contains 0 value, array_search fails if strict parameter not set.

there more 1 bug warnings, rejected motivation: “array_search() loose comparison default”.

ok, resolve little problem using strict parameter...

but question is: there decent, valid reason why in loose comparison 'mary'==0 or 'two'==0 or php madness?

you need set third parameter true use strict comparison. please have @ below explanation:

array_search using == compare values during search

form php doc

if third parameter strict set true array_search() function search identical elements in haystack. means check types of needle in haystack, , objects must same instance.

becasue second element 0 string converted 0 during search

simple test

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

solution use strict option search identical values

$key = array_search("mary", $ar,true);                                   ^---- strict option var_dump($key); 

output

string(4) "key3" 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -