1

I have the following array :

$array = array (
    'a' => 'A',
    'b' => 'B',
    'c' => 'C'
);

I want to understand this behaviour :

// true, normal behaviour, there is a 'A' value in my array
echo array_search('A', $array) === 'a';

// true, normal behaviour, there is no 1 value in my array
echo array_search(1, $array) === false;

// true ???? there is no 0 as value in my array
echo array_search(0, $array) === 'a';

Why does array_search(0, $array) return the first key of my array?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153

1 Answers1

6

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

Most people don't know array_search uses == by default If you want to search for identical element you need to add a strict parameter ... what do i mean ?

If you use

array_search(0, $array) //it would use == and 0 == 'A'

What you need is

array_search(0, $array,true) // it would compare with === 0 !== 'A'
                         ^------------ Strict 
Baba
  • 94,024
  • 28
  • 166
  • 217