0

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.

Wychmire
  • 43
  • 3
  • Is that output to a new array, or must you remove the duplicates from array 1 and array 2? – Martin Dec 17 '19 at 16:08
  • Does this answer your question? [array\_merge & array\_unique](https://stackoverflow.com/questions/4660675/array-merge-array-unique) – Federico klez Culloca Dec 17 '19 at 16:11
  • 1
    If you know that the 2 arrays will always contain those values - `$result = ['bar'];` should do it. – Nigel Ren Dec 17 '19 at 16:15
  • @NigelRen the issue with that is it's not just those three entries, there's 75. I'd like to match and remove 6 of those entries, but that number may increase or decrease with time. – Wychmire Dec 17 '19 at 17:02
  • @FedericoklezCulloca I don't think so. A comment on that question says "[...] this will only work if the keys are [...] guaranteed to be unique between the two arrays, otherwise array_merge will overwrite." Since the order isn't necessarily the same the keys might not be unique. – Wychmire Dec 17 '19 at 17:05

1 Answers1

3

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.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • This works. I found this [answer](https://stackoverflow.com/a/369608/12553344) to a different question, and the \array_diff() method listed there also works. Is this solution or theirs a better option? – Wychmire Dec 17 '19 at 17:11
  • It is the same array_diff method used a single time and for the current example data it would suffice. Only when there are also different values the other way around you could use another array_diff to get those too and then merge them. – The fourth bird Dec 17 '19 at 17:17