在PHP中确定一个变量是否等于数组中的任何变量

3
有没有一种方法可以确定一个变量是否等于数组中任何一个变量的值? 例如,
IF ($a == $b) {
 echo "there is a match";
}
//where $b is an array of values
//and $a is just a single value

你尝试过只是循环遍历数组吗?除了内置函数,这应该是最直接的方法。 - Carcigenicate
所以你基本上想要检查一个数组是否包含某个特定的值? - Debabrata
数组不包含变量,它们包含值。 - Barmar
array_intersect()比in_array()快得多。 - mwweb
5个回答

12

当然有。

if (in_array($a, $b)) {
    echo "there is a match";
}

如果变量$a的类型需要和$b中的值类型匹配,应该使用严格比较来确保不会因为一些误报情况而得到错误的结果。

in_array(0, ['abc', '', 42]) // returns true because 0 == ''

in_array 函数的第三个参数设置为 true 即可实现此功能。

in_array(0, ['abc', '', 42], true)  // returns false because 0 !== ''

那个修复了很多问题...谢谢! - Jeff Sayers
我有 string(1) "2"array(1) { [0]=> array(1) { ["node_id"]=> string(1) "2" } }。但是 if(in_array($res['floor_id'],$result)) { echo "there is a match"; } else { echo "no match"; } 告诉我没有匹配项。 - Faisal Qayyum
1
@FaisalQayyum 看起来字符串“2”不是直接在数组中,而是在数组内的另一个数组中。in_array 不会查找内部数组。对于这种情况,您可以使用 array_filter,像这样:https://3v4l.org/Eag87C - Don't Panic

3

1
您可以使用in_array函数来检查数组中是否存在该值:
in_array('a', array('a', 'b')); // true
in_array('a', array('b', 'c')); // false

1

1

试试这个:

$a = '10';
$b = ['1', 24, '10', '20'];
if (in_array($a, $b)){
    print('find');
}

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