PHP array_search() 函数
实例
在数组中搜索键值 "red",并返回它的键名:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_search("red",$a); ?>
定义和用法
array_search() 函数在数组中搜索某个键值,并返回对应的键名。
详细说明
array_search() 函数与 in_array() 同理,在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回 false。
Before PHP 4.2.0, the function returned null instead of false on failure.
If the third parameter strict If specified as true, the key name of the corresponding element is returned only 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. |
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.
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, the corresponding key name is returned, otherwise FALSE is returned. If the specified 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+ |
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); ?>