PHP array_search()Functions

PHP Array ReferenceComplete PHP Array Reference Manual

Examples

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

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

Run example »

Definition and Usage

The array_search() function is used to search for a value in an array and return the corresponding key name. If the value is not found, it returns false.


Syntax

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Parameter Description
$needle Required. Specifies the key value to search for in the array.
$haystack Required. Specifies the array to be searched.
$strict Optional. Default is false. Only compares values, not types. If this parameter is set to TRUE, the function searches the array for elements whose data type and value are both identical. Possible values:
  • true
  • false - Default
If set to true, the type of the given value is checked 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, the corresponding key name is returned; otherwise, FALSE is returned. If the key value is found more than once in the array, the key name matching the first found key value is returned.
PHP Version: 4.0.5+
Changelog: If an invalid parameter is passed to the function, the function returns NULL (this applies to all PHP functions since PHP 5.3.0).

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


More Examples

Examples

<?php
$numbers = array(1, "2", 3);
$key = array_search(2, $numbers);        // Strict mode is not enabled, returns key name 1
$key_strict = array_search(2, $numbers, true);  // Strict mode is enabled, returns false
?>

Example 1

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

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

Run example »


PHP Array ReferenceComplete PHP Array Reference Manual Other Extensions