vtamm
vtamm

Reputation: 339

How can I check if any value in an array is present in another array?

I have a form that submits an array of user roles for processing by the server. Here is an example of the $data['roles'] posted by the form:

Array ( [0] => 5 [1] => 16 )

I want to check if $data['roles'] contains either one of the values 16, 17, 18 or 19. As you can see in the example it contains 16. in_array seems like the logical choice here, but passing an array of values as the needle of in_array doesn't work:

$special_values = array(16, 17, 18, 19);

if (in_array($special_values, $data['roles'])) {
    // this returns false
}

Neither does passing the exact same values in an array:

$special_values = array(5, 16);

if (in_array($special_values, $data['roles'])) {
    // this also returns false
}

Also, switching places between the two arrays as needle and haystack doesn't change the result. If I just ask if 16 is in the array, it works fine:

$special_value = 16;

if (in_array($special_value, $data['roles'])) {
    // this returns true
}

The documentation gives examples of using arrays as needles, however it seems the structure needs to be exactly the same in the haystack for it to return true. But then I don't get why my second example doesn't work. I'm obviously doing something wrong or missing something here.

What is the best way to check if any of the values in one array exists in another array?

Edit: This question (possible duplicate) is not asking the same thing. I want to match any value in one array against any value in another. The linked question wants to match all values in one array against the values of another.

Upvotes: 0

Views: 212

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

This may help you

Using array_intersect()

$result = array_intersect($data['roles'], array(16, 17, 18, 19));
print_r($result);

Using in_array()

$result = false;

foreach ($special_values as $val) {
    if (in_array($val, $data['roles'], true)) {
        $result = true;
    }
}

Upvotes: 1

Piotr Pasich
Piotr Pasich

Reputation: 2639

The bet way is to use array_diff and empty functions, I think:

if ( ! empty(array_diff($special_values, $data['roles']))) {
    throw new Exception('Some of special values are not in data roles');
}

or array_intersect if you want to return values which occur in both arrays.

Upvotes: 1

Related Questions