php array_search() 函数使用_PHP教程

WBOY
Release: 2016-07-21 15:39:22
Original
888 people have browsed it

定义和用法

array_search() 函数与 in_array() 一样,在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回 false。

在 PHP 4.2.0 之前,函数在失败时返回 null 而不是 false。

如果第三个参数 strict 被指定为 true,则只有在数据类型和值都一致时才返回相应元素的键名。

语法

array_search(value,array,strict)
Copy after login
参数 描述
value 必需。规定在数组中搜索的值。
array 必需。被搜索的数组。
strict

可选。可能的值:

  • true
  • false - 默认

如果值设置为 true,还将在数组中检查给定值的类型。(参见例子 2)


Example #1 array_search() 例子
复制代码 代码如下:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>


Warning
本函数可能返回布尔值 FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如 0 或者 ""。请参阅布尔类型章节以获取更多信息。应使用 === 运算符来测试本函数的返回值。


例子 1
复制代码 代码如下:

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
echo array_search("Dog",$a);
?>

输出:a

例子 2
复制代码 代码如下:

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

输出:
b

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/321549.htmlTechArticle定义和用法 array_search() 函数与 in_array() 一样,在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!