Marc
Marc

Reputation: 493

Check if atleast one array value is in another array PHP

I have an array of 350 values (collected from an API).

Now in order to filter i allow the user to select an unknown amount of countries.

An example of this could be the following

$countries = array
(
    0 => 'Denmark',
    1 => 'Sweden',
    2 => 'United states',
    3 => 'Norway'
);

Now i want to check that atleast one of the values is in my data array

i know that i am able to do this by looping through all of them and checking each individually. but if i could i really want to avoid that.

So is there a way to do such a thing in PHP?

Upvotes: 0

Views: 339

Answers (2)

Dave
Dave

Reputation: 3658

$needles = array(0 => 'Denmark', 1 => 'Sweden');
$haystack = array(0 => 'Denmark', 1 => 'Sweden', 2 => 'United States', 3 => 'Russia');
$found = array_intersect($haystack, $needles);

$found is then:

array(2) {
  [0]=>
  string(7) "Denmark"
  [1]=>
  string(6) "Sweden"
}

You really need to read the manual: http://www.php.net/manual/en/function.array-intersect.php

Upvotes: 1

Schleis
Schleis

Reputation: 43750

There are many array functions in php. You want array_intersect and you can get all the ones listed in both arrays.

http://www.php.net/manual/en/function.array-intersect.php

Upvotes: 4

Related Questions