8

I have an array that is generated with anywhere between 3 and 12 values, it generates the array from account information;

$result = $ad->user()->groups($user['username']);

I want to check this array for multiple values (around 4 or 5) and if any of them are in it do what's inside the if, I can do it for one value pretty easily via:

if (in_array("abc",$result)) {  $this->login_session($user); }

Is there a simple way to check this one array for multiple values in it other than consecutive ORs:

    if (in_array("abc",$result) || in_array("123",$result) || in_array("def",$result) || in_array("456",$result) ) {  
    $this->login_session($user); 
    }
hakre
  • 193,403
  • 52
  • 435
  • 836
toups
  • 235
  • 3
  • 5
  • 10
  • You may pass an array as the search value. – Voitcus Apr 08 '13 at 13:32
  • 4
    @all if you pass `in_array` an array as the needle it only returns true if the needle array is an exact match to an array in the haystack. So to throw OP a bone it is perhaps a little misleading? [see test case](http://codepad.org/fLKLfd0K) – Emissary Apr 08 '13 at 13:45
  • 1
    Thank you Emissary, I was having that exact problem with all of the answers/comments. I need it to be true if ANY of the values are in the array, the suggestions only work as you said if they are an exact match. – toups Apr 08 '13 at 13:50
  • Possible duplicate of [in\_array multiple values](http://stackoverflow.com/questions/7542694/in-array-multiple-values) – T.Todua Aug 27 '16 at 08:57

2 Answers2

22

Try and see if this is helpful:

if(array_intersect($result, array('abc', '123', 'def'))) {
  $this->login_session($user);
}
pilsetnieks
  • 10,330
  • 12
  • 48
  • 60
Mircea Soaica
  • 2,829
  • 1
  • 14
  • 25
2

This should be what you are after:

$a = array(1,2,3,4,5);

$b = array(6,8);

function is_in_array($needle, $haystack) {

    foreach ($needle as $stack) {

        if (in_array($stack, $haystack)) {
             return true;
        }
    }

    return false;
}

var_dump(is_in_array($b, $a));

Basically loops through needle and runs an in array of it on the haystack. returns true once something is found, else it returns false.

Ozzy
  • 10,285
  • 26
  • 94
  • 138