在PHP中,我如何检查一个数组是否包含特定的值?

74

我有一个PHP数组变量,我想知道它是否包含特定的值,并告诉用户它是否存在。 这是我的数组:

Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room) 

我想要做类似这样的事情:

if(Array contains 'kitchen') {echo 'this array contains kitchen';}

如何最好地完成上述操作?


1
in_array 似乎是最好的选择 :) 对于关联数组,还可以看一下 array_key_exists。 - Aram Kocharyan
为什么这个问题被关闭,而链接的那个问题却没有?这个问题的浏览量是链接问题的10倍以上。虽然这个问题稍微晚了一点,但两个问题都已经超过10年了。 - Inertial Ignorance
8个回答

165

使用in_array()函数

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

注意:PHP数组的所有元素不必是相同的数据类型。它们可以是不同的数据类型。如果您想要匹配数据类型,则将true作为in_array的第三个参数传递。 - Omar Tariq
如何在不使用in_array()函数的情况下实现? - user2215270
@user2215270 你可以使用foreach或其他循环控制结构遍历数组,并在每次迭代时检查当前元素。但是,为什么要这样做呢? - Wiseguy

22
// 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

12

请参考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));
    }
?>

3

3

1
以下是您可以这样做的方法:
<?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';
}

如果您希望快速实现此搜索不区分大小写,可以查看此回复中提出的解决方案:https://dev59.com/VIvda4cB1Zd3GeqPZnQP#30555568 来源:http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

1
if (in_array('kitchen', $rooms) ...

0

使用动态变量在数组中进行搜索

 /* 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";
}

else部分不起作用,为什么? - Mohamed Raza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接