如何在php中检查数组是否包含特定值?

时间:2012-01-16 14:52:04

标签: php arrays

我有一个类型为Array的PHP变量,我想知道它是否包含特定值并让用户知道它在那里。这是我的阵列:

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

我想做类似的事情:

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

执行上述操作的最佳方式是什么?

8 个答案:

答案 0 :(得分:126)

使用in_array() function

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

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

答案 1 :(得分:15)

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

答案 2 :(得分:11)

请参阅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)

您需要在阵列上使用搜索算法。这取决于你的阵列有多大,你有很多选择。或者您可以使用内置函数:

http://www.w3schools.com/php/php_ref_array.asp

http://php.net/manual/en/function.array-search.php

答案 4 :(得分:3)

来自http://php.net/manual/en/function.in-array.php

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

使用松散比较搜索haystack针头,除非设置了strict。

答案 5 :(得分:1)

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

答案 6 :(得分: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";

答案 7 :(得分:0)

以下是如何做到这一点:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

确保您搜索厨房而非厨房。此功能区分大小写。因此,以下功能只是简单地工作:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

如果您想要快速方法使此搜索不区分大小写,请查看此回复中提议的解决方案:https://stackoverflow.com/a/30555568/8661779

来源:http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples