13

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?

Community
  • 1
  • 1
Rob
  • 7,980
  • 30
  • 75
  • 115
  • you could disambiguate your question by changing it to: "How can I remove duplicates, _and the values duplicated_, from an array?" – Geoffrey Oct 14 '10 at 16:04

2 Answers2

17

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

array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • +1 for ingenuity, though it's hard to read the intent when you see a line like that! – Paul Dixon Sep 11 '10 at 14:54
  • this is significantly slower than Ciprian's approach though, I just did a quick benchmark and this is 4x slower. A little surprising. – Paul Dixon Sep 11 '10 at 15:03
8

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;
}
Ciprian L.
  • 587
  • 2
  • 7