检查数组中是否存在任何值


Check if any of values exists in array

想要缩短此代码

if( (in_array('2', $values)) or (in_array('5', $values)) or (in_array('6', $values)) or (in_array('8', $values)) ){
echo 'contains 2 or 5 or 6 or 8';
}

尝试过这个

(in_array(array('2', '5', '6', '8'), $values, true))

但据我所知,只有当数组中存在所有值时,才是真的

请告知

尝试array_intersect(),例如

if (count(array_intersect($values, array('2', '5', '6', '8'))) > 0) {
    echo 'contains 2 or 5 or 6 or 8';
}

此处的示例-http://codepad.viper-7.com/GFiLGx

您可以创建这样的函数:

function array_in_array($array_values, $array_check) {
  foreach($array_values as $value)
    if (in_array($value, $array_check))
      return true;
  return false;
}

您甚至可以省略count来缩短代码。

$input = array(2,3);
if (array_intersect($input, $values)) {
    echo 'contains 2 or 3';    
}

怎么样

$targets = array(2,5,6,8);
$isect = array_intersect($targets, $values);
if (count($isect) != 0) {
// do stuff
}