Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove ALL duplicates from an array in PHP?

Tags:

arrays

php

First of all, I'd like to point out to all you duplicate question hunters that this question does not fully answer my question.

Now, I've got an array. We'll say that the array is array(1, 2, 2, 3, 4, 3, 2)

I need to remove the duplicates. Not just one of the duplicates, but all, so that the result will be array(1, 4)

I looked at array_unique(), but that will only result in array(1, 2, 3, 4)

Any ideas?

like image 233
Rob Avatar asked Sep 11 '10 14:09

Rob


People also ask

What removes all duplicate values from array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How are duplicates removed from an array without using any library PHP?

An array is defined and duplicate elements from the array can be found and removed using the 'array_flip' function, that basically reverses the keys/index as values and values as keys.

How do you get unique values in a multidimensional array?

A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.


2 Answers

You could use the combination of array_unique, array_diff_assoc and array_diff:

array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
like image 105
Gumbo Avatar answered Sep 30 '22 03:09

Gumbo



function removeDuplicates($array) {
   $valueCount = array();
   foreach ($array as $value) {
      $valueCount[$value]++;
   }

   $return = array();
   foreach ($valueCount as $value => $count) {
      if ( $count == 1 ) {
         $return[] = $value;
      }
   }

   return $return;
}
like image 20
Ciprian L. Avatar answered Sep 30 '22 04:09

Ciprian L.