Latest web development tutorials

PHP array_search () function

PHP Array Reference Complete PHP Array Reference

Examples

Search key "red" in the array, and returns its key name:

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

Running instance »

Definition and Usage

array_search () function to search for a key value in the array, and returns the corresponding key name.


grammar

array_search( value,array,strict )

参数 描述
value 必需。规定在数组中搜索的键值。
array 必需。规定被搜索的数组。
strict 可选。如果该参数被设置为 TRUE,则函数在数组中搜索数据类型和值都一致的元素。可能的值:
  • true
  • false - 默认
如果设置为 true,则在数组中检查给定值的类型,数字 5 和字符串 5 是不同的(参见实例 2)。

technical details

return value: If it finds the specified key in the array, then returns the corresponding key name, otherwise it returns FALSE. If you find the key in the array more than once, the first time the key is returned to find the matching keys.
PHP version: 4.0.5+
Update log: If an invalid parameter passed to a function, the function returns NULL (this applies to all starting from PHP 5.3.0 PHP function).

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


More examples

Example 1

Search keys in the array 5, and returns its key name (note ""):

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

Running instance »


PHP Array Reference Complete PHP Array Reference