Finding values in arrays with in_array( ) and array_search( )

The in_array( ) function returns true if an array haystack contains a specific value needle:

boolean in_array(mixed needle, array haystack [, boolean strict])

The following example searches the array of integers $smallPrimes for the integer 19:

$smallPrimes = array(3, 5, 7, 11, 13, 17, 19, 23, 29);
if (in_array(19, $smallPrimes))
  echo "19 is a small prime number"; // Always printed

A third, optional argument can be passed that enforces a strict type check when comparing each element with the needle. In the following example in_array( ) by default returns true; however, with strict type checking, the string "19" doesn't match the integer 19 held in the array and returns false:

$smallPrimes = array(3, 5, 7, 11, 13, 17, 19, 23, 29);
if (in_array("19", $smallPrimes, true))
  echo "19 is a small prime number"; // NOT printed

The array_search( ) function-introduced with PHP 4.0.5-works the same way as the in_array( ) function, except the key of the matching value needle is returned rather than the Boolean value true:

mixed array_search(mixed needle, array haystack [, boolean strict])

However, if the value isn't found, array_search( ) returns false. The following fragment shows how array_search( ) works with both associative and indexed arrays:

$measure = array("inch"=>1, "foot"=>12, "yard"=>36);
// prints "foot"
echo array_search(12, $measure);
$units = array("inch", "centimeter", "chain", "furlong");
// prints 2
echo array_search("chain", $units);

Because array_search( ) returns a mixed result-the Boolean value false if the value isn't found or the key of the matching element-a problem is encountered when the first element is found. PHP's automatic type conversion treats the value 0-the index of the first element-as false in a Boolean expression.

Care must be taken with functions, such as array_search( ), that return a result or the Boolean value false to indicate when a result can't be determined. If the return value is used as a Boolean-in an expression or as a Boolean parameter to a function-a valid result may be automatically converted to false. If such a function returns 0, 0.0, "c", an empty string, or an empty array, PHP's automatic type conversion converts the result to false when a Boolean value is required.

The correct way to test the result is to use the is-identical operator ===, as shown in the following example:

$index = array_search("inch", $units);
if ($index === false)
  echo "Unknown unit: inch";
  // OK to use $index
  echo "Index = $index";