4

I have two arrays, for example:

array1={1,2,3,4,5,6,7,8,9};
array2={4,6,9}

Is there any function so that I can determine that array2 fully exists in array1?

I know i can use the in_array() function in a loop but in cases where I will have large arrays with hundreds of elements so I am searching for a function.

Nanne
  • 64,065
  • 16
  • 119
  • 163
Sumit Neema
  • 462
  • 3
  • 18

4 Answers4

11

Try:

$fullyExists = (count($array2) == count(array_intersect($array2, $array1));

The array_intersect.php function will return only elements of the second array that are present in all the other arguments (only the first array in this case). So, if the length of the intersection is equal to the lenght of the second array, the second array is fully contained by the first one.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
1

You can use array_intersect for this, but you have to be a bit careful.

If the array to match has no duplicates, you can use

// The order of the arrays matters!
$isSubset = count(array_intersect($array2, $array1)) == count($array2);

However this will not work if e.g. $array2 = array(4, 4). If duplicates are an issue, you need to also use array_unique:

$unique = array_unique($array2);
// The order of the arrays matters!
$isSubset = count(array_intersect($unique, $array1)) == count($unique);

The reason that the order of the arrays matters is that the array given as the first parameter to array_intersect must have no duplicates. If the parameters are switched around this requirement will move from $array2 to $array1, which is important as it can change the behavior of the function.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

Quick and easy solution:

 array_diff(array(1,2,3,4,5,6,7,8,9),array(4,6,9));

if the return is a empty array, it is in the array otherwise he'll output the items that aren't

EaterOfCode
  • 2,202
  • 3
  • 20
  • 33
0

I didn't try with complex array but comparing work for me

var_dump(array(1,2,3,4,5,6,7,8,9) === array(4,6,9));
var_dump(array(1,2,3,4,5,6,7,8,9) === array(1,2,3,4,5,6,7,8,9));
ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58