(PHP 4 >= 4.0.5, PHP 5)
array_search — 在数组中搜索给定的值,如果成功则返回相应的键名
在 haystack 中搜索
needle 参数并在找到的情况下返回键名,否则返回 FALSE。
Note:
如果
needle是字符串,则比较以区分大小写的方式进行。
Note:
在 PHP 4.2.0 之前, array_search() 在失败时返回
NULL而不是FALSE。
如果可选的第三个参数 strict 为 TRUE,则
array_search() 还将在 haystack
中检查 needle 的类型。
如果 needle 在
haystack
中出现不止一次,则返回第一个匹配的键。要返回所有匹配值的键,应该用
array_keys() 加上可选参数
search_value 来代替。
Example #1 array_search() 例子
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
此函数可能返回布尔值
FALSE,但也可能返回等同于 FALSE 的非布尔值,例如 0 或
""(空串)。请阅读 布尔类型章节以获取更多信息。应使用 ===
运算符 来测试此函数的返回值。
参见 array_keys(), array_values(), array_key_exists() 和 in_array()。
needle
The searched value.
Note:
If
needleis a string, the comparison is done in a case-sensitive manner.
haystack
The array.
strict
If the third parameter strict is set to TRUE
then the array_search() function will search for
identical elements in the
haystack. This means it will also check the
types of the
needle in the haystack,
and objects must be the same instance.
Returns the key for needle if it is found in the
array, FALSE otherwise.
If needle is found in haystack
more than once, the first matching key is returned. To return the keys for
all matching values, use array_keys() with the optional
search_value parameter instead.
| 版本 | 说明 |
|---|---|
| 4.2.0 |
Prior to PHP 4.2.0, array_search() returns NULL
on failure instead of FALSE.
|
Example #2 array_search() example
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>