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

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

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

我想做的是:

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

做到以上几点的最好方法是什么?

158201 次浏览
if (in_array('kitchen', $rooms) ...

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

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

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

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

使用 in_array()功能

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


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

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

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

除非设置了严格的比较,否则使用松散的比较搜索大海捞针。

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

利用动态变量进行数组搜索

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

以下是你如何做到这一点:

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