How to remove duplicates in an array?

How to remove duplicates in an array?

For example, if I had the following array:

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

I want him to become

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

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

+6
source share
5 answers

Depending on the version of PHP, this should work in all versions of PHP> = 4.0.6, since it does not 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 from the drop-down list to select the version of PHP you are using)

This works because:

  • array_count_values will go through the array and create an index for each value and increment it every time it encounters it again.
  • 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 deleted.
  • array_keys discards the value part of the array, creating an array with the values ​​being the keys that were defined. This last step gives you a result that removes all the values ​​that existed more than once in the original array.
+4
source

You can filter them 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 containing the original values ​​and their corresponding frequencies; you select only individual frequencies. The end result is obtained by extracting the keys.

Demo

+4
source

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 ) 
+2
source

PHP offers so many array functions , you just need 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

+2
source

Remove duplicate values ​​from the array.

  array_unique($array) $array = array(4, "4", "3", 4, 3, "3"); $result = array_unique($array); print_r($result); /* Array ( [0] => 4 [2] => 3 ) */ 
+1
source

Source: https://habr.com/ru/post/944271/


All Articles