How can I use in_array if the needle is an array?

Donny Kurnia picture Donny Kurnia · Feb 21, 2010 · Viewed 38.7k times · Source

I have 2 arrays, the value will be loaded from database, below is an example:

$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);

What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:

$arr3 = array(1,2,4,5,6,7);

comparing $arr1 with $arr3 will return a FALSE.

Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.

UPDATE for clarification.

First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.

Answer

cletus picture cletus · Feb 21, 2010

Use array_diff():

$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
  // all of $arr1 is in $arr2
}