Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_search return wrong key [duplicate]

Tags:

arrays

php

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?

like image 666
LVA Avatar asked Feb 26 '16 10:02

LVA


Video Answer


2 Answers

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"
like image 115
Chetan Ameta Avatar answered Oct 20 '22 00:10

Chetan Ameta


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

like image 4
Max Zuber Avatar answered Oct 19 '22 22:10

Max Zuber