0

I have the following two arrays:

array(1) { [0]=> array(2) { ["foo"]=> string(4) "Test" ["bar"]=> string(18) "Test" } } 

array(3) { [0]=> array(2) { ["foo"]=> string(3) "295" ["bar"]=> string(1) "9" } [1]=> array(2) { ["foo"]=> string(7) something" ["bar"]=> string(17) "something else" } [2]=> array(2) { ["foo"]=> string(5) "Test2" ["bar"]=> string(19) "Test2" } }

array_diff($arr1, $arr2); returns empty array, where $arr1 and $arr2 are accordingly first and second arrays var dumped here.

Why is that so?

The code is:

$arr1 = array(
    array('foo' => 'Test', 'bar' => 'Test')
);

$arr2 = array(
      array('foo' => '295', 'bar' => '9'),
      array('foo' => 'something', 'bar' => 'else'),
      array('foo' => 'Test2', 'bar' => 'Test2')
);

var_dump(array_diff($arr1, $arr2));
khernik
  • 2,059
  • 2
  • 26
  • 51

2 Answers2

0

This function only checks one dimension of a n-dimensional array.

You can try some other way like -

$op= [];
foreach($arr2 as $array) {
   $check = array_diff($arr1[0], $array);
   $op[]= $check;
}
$op= array_filter($op);

$op = (count($op) === count($arr2)) ? $arr1 : null;

Check it here

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

You can use this

$result = check_diff_multi($arr1, $arr2);
print '<pre>';
print_r($result);
print '</pre>';

function check_diff_multi($array1, $array2){
    $result = array();
    foreach($array1 as $key => $val) {
         if(isset($array2[$key])){
           if(is_array($val) && $array2[$key]){
               $result[$key] = check_diff_multi($val, $array2[$key]);
           }
       } else {
           $result[$key] = $val;
       }
    }

return $result;

}

Ninju
  • 2,522
  • 2
  • 15
  • 21