I've spent hours trying to use array_diff, array_unique, writing foreach loops and anything else I can find and I can't get anything work, the result is always wrong.
Say I have these two arrays:
$arr_a = ['mary', 'mary', 'mary', 'jack', 'jack', 'jack', 'jack', 'fred', 'fred'];
$arr_b = ['mary', 'mary', 'jack', 'jack'];
I need returned:
['mary', 'jack', 'jack', 'fred', 'fred'];
I need the 'leftover' values after the matching values are canceled out, along with those that are completely unique. In $arr_a, we have 3 mary and 4 jack and 2 fred. If you subtract the 2 mary and 2 jack from that, you're left with 1 mary, 2 jack and 2 fred.
My actual use case is comparing thousands of product id's to thousands of product id's. Given that there can be anywhere from 2-100+ duplicate product id's, things like array_diff array_unique etc are not working.
I have tried the following:
array_diff($arr_a, $arr_b);
Doesn't work. It removes all matching values regardless of how many times they occur.
I have tried:
foreach ($arr_a as $a) {
$key = array_search($a, $arr_b);
if ($key) unset($arr_b[$key]);
}
return $arr_b;
When I attempt to use this on very large arrays, the results are never perfect. I've tried a series of checks to weed out false positives and negatives but even those don't always work.
While a similar question to this was asked and received an answer seven years ago, the answer there is what I came up with on my own with the exception of an explicit check for unset(FALSE). Even with that check, it still does not work perfectly on the very large arrays I am passing. In short: that answer from seven years ago is wrong. The one I received here appears to be correct as it works.