in_array多个值

dar*_*ryl 99 php arrays

如何检查多个值,例如:

$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)

  • 这个解决方案不是最好的:$ needles = array(1,2); $草堆=阵列(1,1,2,3); return(count(array_intersect($ haystack,$ needles))== count($ needle)); 这将返回false,这是不好的.Rok Kralj的解决方案适合这种情况. (10认同)
  • 我认为这些数组应该保存唯一的数据,否则这个解决方案将不起作用 (3认同)

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)

  • 注意:这种类型的数组声明是> = PHP 5.4 (8认同)
  • 这是IMO的最佳答案 (4认同)

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)

  • 解决方案恕我直言 如果新值加上动态,则不进行缩放... (20认同)

sMy*_*les 6

从@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

  • 作为对Rok答案的评论,它比作为新答案更有用。 (8认同)