views:

184

answers:

3

I have 2 array, the value will be from database, below is the case 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 values in $arr1 is 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 are any simple way to do the checking with a minimum looping.

UPDATE for clarification.

First array will be a set that contain unique values. Second array can contains duplicated values. Both is guaranteed an array before processed.

TIA

+3  A: 

You can try use the array_diff() function to find the difference between the two arrays, this might help you. I think to clarify you mean, all the values in the first array must be in the second array, but not the other way around.

Sam152
Yes Sam. All `$arr1` values must be appear in second array, to get a `TRUE` condition, otherwise, `FALSE`. I'll take a look for the `array_diff()`. Thanks
Donny Kurnia
+6  A: 

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
}
cletus
+1 for point me to `array_diff()` function and give usage example.
Donny Kurnia
+4  A: 

You can use array_intersect or array_diff:

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

if ( $arr1 == array_intersect($arr1, $arr2) ) {
    // All elements of arr1 are in arr2
}

However, if you don't need to use the result of the intersection (which seems to be your case), it is more space and time efficient to use array_diff:

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

if ( empty($diff) ) {
    // All elements of arr1 are in arr2
}
Justin Johnson
+1 for pointed to `array_intersect()` functions and giving the usage example.
Donny Kurnia