PHP array_search() function

Example

Search for the key value "red" in the array and return its key name:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>

Run Examples

Definition and usage

The array_search() function searches for a key value in an array and returns the corresponding key name.

Detailed description

The array_search() function is with in_array() Similarly, to find a key value in an array. If the value is found, the key name of the matching element will be returned. If not found, then false is returned.

Before PHP 4.2.0, the function returned null instead of false on failure.

If the third parameter strict If specified as true, it only returns the key name of the corresponding element when the data type and value are both consistent.

Syntax

array_search(value,array,strict)
Parameters Description
value Required. Specifies the key value to be searched for.
array Required. Specifies the array to be searched.
strict

Optional. If this parameter is set to TRUE, the function searches for elements in the array that have the same data type and value.

  • true
  • false - Default

If set to true, the function checks the type of the given value in the array, the number 5 and the string 5 are different (see example 2).

Technical Details

Return Value:

If the specified key value is found in the array, it returns the corresponding key name, otherwise it returns FALSE.

If the specified key value is found more than once in the array, it returns the key name corresponding to the first found key value.

PHP Version: 4.0.5+
Update Log:

If invalid parameters are passed to the function, the function returns NULL (this applies to all PHP functions starting from PHP 5.3.0).

Starting from PHP 4.2.0, if the search fails, the function returns FALSE instead of NULL.

More Examples

Example 1

Search for the key value 5 in the array and return its key name (note ""):

<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>

Run Examples