6

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?

LVA
  • 103
  • 6
  • 1
    I think it stop search when got first equals. If put `key3` before `key2` (`$ar = [ 'key1'=>'John', 'key3'=>'Mary', 'key2'=>0];`) `array_search` will return `key3`. – brevis Feb 26 '16 at 11:03
  • 2
    As said in the [array_search()](http://php.net/manual/en/function.array-search.php) manual... You need to set the 3th parameter if the search needs to be strict... – Naruto Feb 26 '16 at 11:03
  • 2
    @Naruto Yes, I write it in my question. My question is about 'why?', not 'how'... – LVA Feb 26 '16 at 11:07
  • 3
    @LVAmeda because int of any string is equal to zero – splash58 Feb 26 '16 at 11:09
  • 1
    Strict comparison is not using == it's using === ... That's basically the point of strict.. – Naruto Feb 26 '16 at 11:10
  • 1
    @splash58 that is the answer, I think... Thank you! – LVA Feb 26 '16 at 11:14
  • 1
    @Naruto yes, Naruto, I well know. My point was another... :) – LVA Feb 26 '16 at 11:15

4 Answers4

12

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"
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
4

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

Max Zuber
  • 1,217
  • 10
  • 16
-1

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

Vadivel S
  • 660
  • 8
  • 15
-1
  $ar = [ 'key1'=>'John', 'key2'=>'0', 'key3'=>'Mary' ];
Sushant Yadav
  • 726
  • 1
  • 13
  • 28
keerti Sawlani
  • 233
  • 1
  • 9