如何检查多个值,例如:
$arg = array('foo','bar');
if(in_array('foo','bar',$arg))
这是一个例子,所以你可以更好地理解,我知道它不会起作用。
发布于 2011-09-25 07:51:51
将目标与干草堆相交,并确保相交恰好等于目标:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
请注意,您只需验证结果交集的大小与目标值数组的大小相同,即可确定$haystack
是$target
的超集。
要验证$haystack
中是否也存在$target
中的至少一个值,可以执行以下检查:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
发布于 2012-06-15 04:08:03
作为一名开发人员,您可能应该开始学习集合操作(差、并、交)。你可以把你的数组想象成一个“集合”,而你正在搜索的密钥则是另一个。
检查是否所有的针都存在
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present
检查针头是否存在
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present
发布于 2011-09-25 07:51:07
if(in_array('foo',$arg) && in_array('bar',$arg)){
//both of them are in $arg
}
if(in_array('foo',$arg) || in_array('bar',$arg)){
//at least one of them are in $arg
}
https://stackoverflow.com/questions/7542694
复制相似问题