2017-09-15 61 views
0

有没有办法确定一个变量是否等于数组中的任何变量的值? 例如,确定变量是否等于数组中的任何变量php

IF ($a == $b) { 
echo "there is a match"; 
} 
//where $b is an array of values 
//and $a is just a single value 
+0

你有没有试过只循环数组?没有内置的,这将是直接的方式。 – Carcigenicate

+0

所以基本上你想检查一个数组是否包含某个值? – Debabrata

+0

数组不包含变量,它们包含值。 – Barmar

回答

6

Sure there is.

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 !== '' 
+0

快得多......谢谢! –

1

可以检查使用in_array function阵列中存在的值:

in_array('a', array('a', 'b')); // true 
in_array('a', array('b', 'c')); // false 
1

尝试这种情况:

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