1

I noticed something interesting about the PHP array_search function and was wondering if someone could tell me how to solve this issue:

It says in the docs that that the function returns the key when the value is found in the array, and false otherwise.

The problem is that if you have an array such as:

$arr = array(0 => "red", 1 => "blue", ...);

and look for the value red using array_search, then the key 0 will returned.

However the problem is that if you use the result of the function to find whether some element was found in the array, then if the value returns 0 (the key 0 because an element was actually found which has the key 0), it's treated the same in PHP as when the function return false. In other words:

if (array_search("red", $arr) == false)

if the same as:

if (array_search("red", $arr) == 0)

excepted that in one case, the element couldn't be found and in the second case, an element was maybe found which key was 0.

So my question is, what's the solution to this problem?

user18490
  • 3,073
  • 3
  • 24
  • 49

1 Answers1

4

In the PHP manual:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Pedro Amaral Couto
  • 1,138
  • 8
  • 8