0

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?

4
  • Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. Commented Oct 9, 2013 at 14:51
  • Sweden is spelled wrong. Just saying ;) Commented Oct 9, 2013 at 14:52
  • Yeah i know i'm sorry. :) Commented Oct 9, 2013 at 14:53
  • Are you trying to compare two arrays? Your question is missing something. It seems you're trying to compare one array to the other, but you've only provided one array in your question. What are you working with, and what are the intended results? Commented Oct 9, 2013 at 14:56

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

The array_intersect checks if all the values of one array is in the other. i just want to check if ATLEAST 1 value is present
@Marc Just check if the returned array of the intersect has a count > 0
So something like this: count(array_intersect($country_array, $data['Country']['Name'])) > 0
1
$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.