phparraysfilter

PHP - Compare two arrays and if there are duplicates remove all matches


I have two arrays:

foo
bar
baz

and

foo
baz

I'd like to compare these two arrays and if there are matches, remove both matches (not just duplicates) so I end up with an array like this:

bar

I know that array 1 will always contain foo, bar, and baz and that array 2 will always contain foo and baz. The entries in the array won't always be in the same order but the contents will stay the same.

Instead of comparing the two arrays I could do something like the solution of 16153948, but that would require me to use a (almost) duplicate line for each match I want to remove since the entries are fairly unrelated (can't use regex), which doesn't seem like a good solution.


Solution

  • You could get the differences of both arrays using array_diff and then merge them using array_merge:

    $res = array_merge(array_diff($a, $b), array_diff($b, $a));
    print_r($res);
    

    Php demo

    Output

    Array
    (
        [0] => bar
    )
    

    Php demo with more different values.