我有一个PHP数组变量,我想知道它是否包含特定的值,并告诉用户它是否存在。 这是我的数组:
Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)
我想要做类似这样的事情:
if(Array contains 'kitchen') {echo 'this array contains kitchen';}
如何最好地完成上述操作?
我有一个PHP数组变量,我想知道它是否包含特定的值,并告诉用户它是否存在。 这是我的数组:
Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)
我想要做类似这样的事情:
if(Array contains 'kitchen') {echo 'this array contains kitchen';}
如何最好地完成上述操作?
使用in_array()
函数。
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
if (in_array('kitchen', $array)) {
echo 'this array contains kitchen';
}
true
作为in_array
的第三个参数传递。 - Omar Tariqforeach
或其他循环控制结构遍历数组,并在每次迭代时检查当前元素。但是,为什么要这样做呢? - Wiseguy// Once upon a time there was a farmer
// He had multiple haystacks
$haystackOne = range(1, 10);
$haystackTwo = range(11, 20);
$haystackThree = range(21, 30);
// In one of these haystacks he lost a needle
$needle = rand(1, 30);
// He wanted to know in what haystack his needle was
// And so he programmed...
if (in_array($needle, $haystackOne)) {
echo "The needle is in haystack one";
} elseif (in_array($needle, $haystackTwo)) {
echo "The needle is in haystack two";
} elseif (in_array($needle, $haystackThree)) {
echo "The needle is in haystack three";
}
// The farmer now knew where to find his needle
// And he lived happily ever after
请参考in_array
<?php
$arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");
if (in_array("kitchen", $arr))
{
echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
}
?>
从http://php.net/manual/zh/function.in-array.php
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
如果未设置 strict,则使用松散的比较在 haystack 中查找 needle。
<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
echo 'this array contains kitchen';
}
请确保搜索kitchen而不是Kitchen。此函数区分大小写。因此,以下函数将无法正常工作:
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
echo 'this array contains kitchen';
}
if (in_array('kitchen', $rooms) ...
使用动态变量在数组中进行搜索
/* https://ideone.com/Pfb0Ou */
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
/* variable search */
$search = 'living_room';
if (in_array($search, $array)) {
echo "this array contains $search";
} else {
echo "this array NOT contains $search";
}