Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Duplicates while Using array_diff

Tags:

arrays

php

I am using array_diff() to take values out of array1 which are found in array2. The issue is it removes all occurrences from array1, as the PHP documentations makes note of. I want it to only take out one at a time.

$array1 = array();
$array1[] = 'a';
$array1[] = 'b';
$array1[] = 'a';

$array2 = array();
$array2[] = 'a';

It should return an array with one 'a' and one 'b', instead of an array with just 'b';

like image 774
STEELHE4RT Avatar asked Jun 06 '13 22:06

STEELHE4RT


1 Answers

Just for the fun of it, something that just came to mind. Will work as long as your arrays contain strings:

$a = array('a','b','a','c');
$b = array('a');

$counts = array_count_values($b);
$a = array_filter($a, function($o) use (&$counts) {
    return empty($counts[$o]) || !$counts[$o]--;
});

It has the advantage that it only walks over each of your arrays just once.

See it in action.

How it works:

First the frequencies of each element in the second array are counted. This gives us an arrays where keys are the elements that should be removed from $a and values are the number of times that each element should be removed.

Then array_filter is used to examine the elements of $a one by one and remove those that should be removed. The filter function uses empty to return true if there is no key equal to the item being examined or if the remaining removal count for that item has reached zero; empty's behavior fits the bill perfectly.

If neither of the above holds then we want to return false and decrement the removal count by one. Using false || !$counts[$o]-- is a trick in order to be terse: it decrements the count and always evaluates to false because we know that the count was greater than zero to begin with (if it were not, || would short-circuit after evaluating empty).

like image 102
Jon Avatar answered Oct 09 '22 00:10

Jon