PHP in_array() 函数
说明
in_array() 函数检查数组中是否存在值。
下表总结了该函数的技术细节。
| 返回值: | 如果在数组中找到搜索值,则返回 TRUE,否则返回 FALSE。 |
|---|---|
| 版本: | PHP 4+ |
语法
in_array() 函数的基本语法如下:
in_array(search, array, strict);
以下示例显示了 in_array() 函数的作用。
<?php
// 样本数组
$colors = array("red", "green", "blue", "orange", "yellow");
// 在颜色数组中搜索值
if(in_array("orange", $colors)){
echo "Match found!";
} else{
echo "No match found!";
}
?>
参数
in_array() 函数接受以下参数。
| 参数 | 说明 |
|---|---|
| search | 必填。 指定搜索的值。 如果是字符串,则以区分大小写的方式进行比较。 |
| array | 必填。 指定要搜索的数组。 |
| strict | 可选的。 确定在 value 搜索期间是否应使用严格比较 (===)。 可能的值为 true 和 false。 默认值为 false。 |
更多示例
这里有更多示例展示了 in_array() 函数的实际工作原理:
以下示例还将使用 strict 参数匹配搜索值的类型。
<?php
// 样本数组
$numbers = array(5, 7, "10", 12, 15, "18", 20);
// 在数字数组中搜索值
if(in_array("15", $numbers, true)){
echo "Match found!";
} else{
echo "No match found!";
}
?>
您还可以将数组作为搜索参数传递,如下例所示:
<?php
// 样本数组
$mixed = array(array("a", "b"), array("x", "y"), "z");
// 在混合数组中搜索值
if(in_array(array("x", "y"), $mixed)){
echo "Match found!";
} else{
echo "No match found!";
}
?>
Advertisements
