检查数组中是否有多个值

时间:2011-07-28 20:54:52

标签: php arrays

我想检查数字7,86和99是否存在于名为$category的数组中。

到目前为止,我有这个,但我不想用三行来完成它:

if (in_array("7", $category)) {  //do something  }

3 个答案:

答案 0 :(得分:3)

$search = array("7", "86", "99");

如果id是$category变量的键:

if (count(array_intersect($search, array_keys($category))) == count($search)) {
  // all found
}
if (count(array_intersect($search, array_keys($category))) > 0) {
  // some found
}

如果id是$category变量的值:

if (count(array_intersect($search, $category)) == count($search)) {
  // all found
}
if (count(array_intersect($search, $category)) > 0) {
  // some found
}

答案 1 :(得分:2)

array_diff比较数组m,n并返回m中不包含n的任何元素。

count( array_diff( array(7,86,99), $category ) )

答案 2 :(得分:1)

if (in_array("7", $category) + in_array("86", $category) + in_array("99", $category) >= 2)
   echo "at least two is exist in the array";

更新:使用>= 1||