4

I have 2 array , the second array must contain all the element in first array , how to check this ? Thank 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 
user782104
  • 13,233
  • 55
  • 172
  • 312

4 Answers4

4

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

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

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

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
2

array_diff can 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";
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1
$invalid = false;
foreach ($array1 as $key => $value) {
    if (!array_key_exists($key, $array2)) {
        $invalid = true;
        break;
    }
}
var_dump($invalid); 
adrien
  • 4,399
  • 26
  • 26
0

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

ErJab
  • 6,056
  • 10
  • 42
  • 54