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)

4
  • what is your expected output? Commented May 26, 2014 at 10:18
  • for the above sample, system should say the different, Commented May 26, 2014 at 10:19
  • 1
    array_diff() supports only one dimension Commented May 26, 2014 at 10:22
  • 1
    As for recursion, there exists a similar, answered question. 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) Commented May 26, 2014 at 10:24

1 Answer 1

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

echo '<pre>';
print_r($results);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.