in_array 函数基本用法与参数说明
in_array
(PHP 4, PHP 5)
in_array — 检查数组中是否存在某个值
说明
代码如下:bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
该函数在 haystack 数组中查找 needle 值,若存在则返回 TRUE,否则返回 FALSE。
当第三个参数 strict 设为 TRUE 时,in_array() 不仅检查值是否相等,还会严格比对 needle 与 haystack 中元素的类型是否完全相同。
注意:若 needle 为字符串,比较过程区分大小写。
注意:在 PHP 版本 4.2.0 之前,needle 参数不允许传入数组。
Example #1 in_array() 例子
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?> 第二个条件因 in_array() 区分大小写而失败,因此上述程序输出如下:
Got Irix
Example #2 in_array() 严格类型检查例子
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?> 上述示例将输出:
1.13 found with strict check
Example #3 in_array() 中用数组作为 needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?> 上述示例将输出:
'ph' was found
'o' was found
需要注意的地方:
假如:
先声明一个数组为:
$arr = array(*);那么则有:
in_array(0, $arr) == true
令人费解! {弱语言}
解决办法:
in_array(strval(0), $arr, true))