2

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?

DiegoDD
  • 1,625
  • 4
  • 21
  • 32

2 Answers2

1

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);
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
1

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • In fact, little after posting my question, I found this same solution, it was included on a comment on the php array_unique docs, [here](http://mx2.php.net/manual/en/function.array-unique.php#95203) . It works as expected (gives `[2,4,6]` in my example), although as you say, it's not that easy to understand how it works. – DiegoDD Jul 18 '14 at 21:08
  • update, in fact, using just the inner part of the solution `$c = array_diff_assoc($a,array_unique($a))` , you get my other expected result `[2,4,6,6]`, yay! – DiegoDD Jul 18 '14 at 21:13