有没有办法确定一个变量是否等于数组中任何变量的值? 例如,
IF ($a == $b) {
echo "there is a match";
}
//where $b is an array of values
//and $a is just a single value
答案 0 :(得分:6)
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 !== ''
答案 1 :(得分:1)
您可以使用in_array function:
检查数组中是否存在该值in_array('a', array('a', 'b')); // true
in_array('a', array('b', 'c')); // false
答案 2 :(得分:1)
$b = array("Mac", "NT", "Irix", "Linux");
$a = "single string"
if (in_array($a, $b)) {
echo "Yes single string is in array";
}
这是php手册中的描述:http://php.net/manual/en/function.in-array.php
答案 3 :(得分:1)
试试这个:
$a = '10';
$b = ['1', 24, '10', '20'];
if (in_array($a, $b)){
print('find');
}
答案 4 :(得分:1)
试试这个
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>