user2465936
user2465936

Reputation: 1040

Check if any of values exists in array

Want to shorten this code

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';
}

Tried this

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

but as i understand true is only if all the values exists in array

Please, advice

Upvotes: 2

Views: 76

Answers (4)

Kulikov Alexei
Kulikov Alexei

Reputation: 139

You can even omit count to shorten your code.

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

Upvotes: 1

user1864610
user1864610

Reputation:

How about

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

Upvotes: 0

Kevin
Kevin

Reputation: 1000

You can make a function like this :

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

Upvotes: 1

Phil
Phil

Reputation: 164766

Try array_intersect(), eg

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

Example here - http://codepad.viper-7.com/GFiLGx

Upvotes: 5

Related Questions