DiegoDD
DiegoDD

Reputation: 1665

getting duplicate entries from array (instead of just removing them)

I have an array with possible duplicate values, and I want not only to remove them (i use array_unique for that), but extract them in anothr array.

i.e.

$a = array(1,2,2,3,4,4,5,6,6,6);
$b = array_unique($a); // has 1,2,3,4,5,6

I want a third array ($c) with the duplicates only

that is, with [2,4,6] or [2,4,6,6] (either would do)

whats the easiest way of doing it?

I tried $c = array_diff($a,$b), but gives an empty array, since it is removing all of the occurrences of $b from $a (because, of course, they occur at least once in $b)

I also thought of array_intersect, but it result in an array exactly like $a

Is there a direct function in php to achieve this? How to do it?

Upvotes: 2

Views: 52

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32392

You can use array_count_values to count the # of occurrences of each element and use array_filter to only keep those that occur more than once.

$a = array(1,2,2,3,4,4,5,6,6,6);
$b = array_count_values($a);
$c = array_filter($b,function($val){ return $val > 1; });
$c = array_keys($c);
print_r($c);

If your input array is sorted you can find dupes by looping through the array and checking if the previous element is equal to the current one

$a = array(1,2,2,3,4,4,5,6,6,6);
$dupes = array();

foreach($a as $i => $v) {
    if($i > 0 && $a[--$i] === $v)
        $dupes[] = $v;
}

print_r($dupes);

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

I also found such solution on Internet:

$c = array_unique( array_diff_assoc( $a, array_unique( $a ) ) );

But it doesn't seem easy to understand

Upvotes: 1

Related Questions