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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 . 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.
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!
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.