6

How can I delete duplicates in array?

For example if I had the following array:

$array = array('1','1','2','3');

I want it to become

$array = array('2','3');

so I want it to delete the whole value if two of it are found

Ali
  • 3,479
  • 4
  • 16
  • 31
  • http://php.net/array_count_values <- I would try to write something with this function first. It counts at least how often one value has been used. Nicely keyed. – hakre May 04 '13 at 08:49
  • Check out http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php – bestprogrammerintheworld May 04 '13 at 09:28

5 Answers5

4

You can filter them out using array_count_values():

$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
    return $freq == 1;
}));

The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.

Demo

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
4

Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:

function moreThanOne($val) {
    return $val < 2;
}


$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));

DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)

This works because:

  1. array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
  2. array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
  3. array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
Jon
  • 4,746
  • 2
  • 24
  • 37
2

Try this code,

<?php
  $array = array('1','1','2','3');

 foreach($array as $data){
  $key= array_keys($array,$data);
   if(count($key)>1){

  foreach($key as $key2 => $data2){
    unset($array[$key2]);
      }
    }
   }
   $array=array_values($array);
   print_r($array);


?>

Output

    Array ( [0] => 2 [1] => 3 )
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
2

PHP offers so many array functions, you just have to combine them:

$arr = array_keys(array_filter(array_count_values($arr), function($val) {
    return $val === 1;
}));

Reference: array_keys, array_filter, array_count_values

DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

Remove duplicate values from an array.

 array_unique($array)

 $array = array(4, "4", "3", 4, 3, "3");
 $result = array_unique($array);
 print_r($result);

 /*
   Array
   (
      [0] => 4
      [2] => 3
   )
  */
Vinit Kadkol
  • 1,221
  • 13
  • 12