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
  • 12,597
  • 53
  • 165
  • 300

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
  • 260,803
  • 45
  • 432
  • 377
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
  • 311,322
  • 76
  • 447
  • 566
1
$invalid = false;
foreach ($array1 as $key => $value) {
    if (!array_key_exists($key, $array2)) {
        $invalid = true;
        break;
    }
}
var_dump($invalid); 
adrien
  • 4,349
  • 24
  • 26
0

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

ErJab
  • 5,538
  • 9
  • 38
  • 52