【问题标题】:php multiple array values in_array [duplicate]php多个数组值in_array [重复]
【发布时间】:2014-07-26 21:45:52
【问题描述】:

我不确定是否可以使用 in_array。我需要的是验证所有给定的值是否存在于数组中。例如:

$a = array(1,2,3,4,5,6,7,8,9,10)
$b = array(1,2,3);

if(in_array($b, $a)) {
   return true
} else {
  return false
}

请注意,$b 中的所有值都必须存在于 $a 中才能返回 true。

【问题讨论】:

  • 也许在 foreach 中遍历 $b,然后使用 in_array 进行测试?
  • 试试array_intersectarray_diff

标签: php arrays


【解决方案1】:

试试这个:

function arrayExists($needle, $haystack) {
    return sizeof(array_intersect($needle, $haystack)) == sizeof($needle);
}

如果你的 needle 数组有重复值,也可以使用它:

function arrayExists($needle, $haystack) {
    return sizeof(array_intersect(array_unique($needle), array_unique($haystack))) == sizeof(array_unique($needle));
}

【讨论】:

    【解决方案2】:
    $a = array(1,2,3,4,5,6,7,8,9,10);
    $b = array(1,2,3);
    
    if(!array_diff($b, $a)) {
       echo '$b is subset of $a';
    } else {
      echo '$b isn`t subset of $a';
    }
    

    【讨论】:

      【解决方案3】:

      Here 重复

      使用 array_diff()

      $arr1 = array(1,2,3);
      $arr2 = array(1,2,3,4,5,6,7);
      $arr3 = array_diff($arr1, $arr2);
      if (count($arr3) == 0) {
        // all of $arr1 is in $arr2
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-05
        • 2013-03-30
        • 2011-11-24
        • 2022-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        相关资源
        最近更新 更多