如何检查多个值,例如:
$arg = array('foo','bar');
if(in_array('foo','bar',$arg))
Run Code Online (Sandbox Code Playgroud)
这是一个例子,所以你了解得更好,我知道它不会起作用.
Mar*_*iot 192
将目标与干草堆相交,并确保交叉点与目标精确相等:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
Run Code Online (Sandbox Code Playgroud)
请注意,您只需要验证生成的交集的大小是否与目标值数组的大小相同,以表示它$haystack是超集$target.
为了确认至少有一个值,$target也是$haystack,你可以这样做检查:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
Run Code Online (Sandbox Code Playgroud)
Rok*_*alj 161
作为开发人员,您应该开始学习集合操作(差异,联合,交集).您可以将数组想象为一个"集合",以及您正在搜索另一个的键.
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Ria*_*iaD 13
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
}
Run Code Online (Sandbox Code Playgroud)
从@Rok Kralj答案(最佳IMO)出发,检查大海捞针中是否有任何针头,可以使用(bool)代替!!,有时在代码检查期间可能会造成混淆。
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
Run Code Online (Sandbox Code Playgroud)
https://glot.io/snippets/f7dhw4kmju