Check if the array contains the entire element of another array?

I have 2 array, the second array should contain the whole element in the first array, how to check this? Thanks you

For example array 1: Array ( [0] => Email [1] => 1_Name ) array 2: Array ( [0] => 1_Name [1] => ) In this case it is invalid , as array 2 do not have Email array 1: Array ( [0] => Email [1] => 1_Name ) array 2: Array ( [0] => 1_Name [1] => Address [2]=> Email ) In this case it is valid 
+4
source share
4 answers

Use array_intersect() and check that its output is the same length:

 if (count(array_intersect($arr1, $arr2)) === count($arr1)) { // contains all } 

For an associative array, where the keys must also match, use array_intersect_assoc() instead.

+4
source

array_diff may be useful here.

 if( array_diff($array1,$array2)) { // array1 contains elements that are not in array2 echo "invalid"; } else { // all elements of array1 are in array2 echo "valid"; } 
+2
source
 $invalid = false; foreach ($array1 as $key => $value) { if (!array_key_exists($key, $array2)) { $invalid = true; break; } } var_dump($invalid); 
+1
source

There array_intersect() , as Michael suggested. If you want to know which element is missing, you can use array_diff() .

0
source

Source: https://habr.com/ru/post/1411151/


All Articles