Alain Tiemblo Alain Tiemblo - 1 year ago 67
PHP Question

array_search does not work as expected

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?

Answer Source


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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download