0

How find difference of the two array

// ARRAY 1

$a1 = array(
    "a1" => 1,
    "a3" => array(
        "a31" => 31
    ),
    "a4" => array(
        "a41" => 41
    ),
    "a5" => array(
        "a51" => 51,
        "a52" => 52
    )
);

// ARRAY 2
$a2 = array(
    "a1" => 1,
    "a2" => 2,
    "a3" => array(
        "a31" => 31,
        "a32" => array(
            "a321" => 321,
            "a322" => 322
        )
    ),
    "a4" => array(
        "a41" => 42
    ),
    "a5" => array(
        "a51" => 51,
        "a52" => 52
    )
);

array_diff function returns ==> Array ( )

But there is a lot of difference exist in the above two array variables.

example:

  1. in ARRAY1 There is no key a2 but in ARRAY2 a2 is available.
  2. ARRAY2 a3 contain nested array (one nested level ) but in ARRAY 2 contain two nested sub level.

So here i want to compare two array n-level (ie. nested array)

Bharanikumar
  • 25,457
  • 50
  • 131
  • 201
  • what is your expected output? – Satish Sharma May 26 '14 at 10:18
  • for the above sample, system should say the different, – Bharanikumar May 26 '14 at 10:19
  • 1
    `array_diff()` supports only one dimension –  May 26 '14 at 10:22
  • 1
    As for recursion, there exists a [similar, answered question](http://stackoverflow.com/questions/3876435/recursive-array-diff). Note that the "difference" in both directions cannot be expressed in a single array, since you both have "subtracted" and "added" members. If you want to merge these changes to one array (losing whether a key was "added" or "subtracted"), you could `array_merge_recursive(array_diff_recursive($a1, $a2), array_diff_recursive($a2, $a1))` ([documentation](http://www.php.net/manual/en/function.array-merge-recursive.php)) – Lukas May 26 '14 at 10:24

1 Answers1

1
$results = array_diff(array_map('serialize',$a2),array_map('serialize',$a1));
$results = array_map('unserialize',$results);

echo '<pre>';
print_r($results);
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91