How to remove duplicate values from an array in PH

2018-12-31 08:12发布

How can I remove duplicate values from an array in PHP?

21条回答
谁念西风独自凉
2楼-- · 2018-12-31 08:57

There can be multiple ways to do these, which are as follows

//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));

//second method
$array = array_unique($arr, SORT_REGULAR);
查看更多
君临天下
3楼-- · 2018-12-31 08:58
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];    
print_r(arr_unique($arr1));


function arr_unique($arr) {
  sort($arr);
  $curr = $arr[0];
  $uni_arr[] = $arr[0];
  for($i=0; $i<count($arr);$i++){
      if($curr != $arr[$i]) {
        $uni_arr[] = $arr[$i];
        $curr = $arr[$i];
      }
  }
  return $uni_arr;
}
查看更多
明月照影归
4楼-- · 2018-12-31 09:00
//Find duplicates 

$arr = array( 
    'unique', 
    'duplicate', 
    'distinct', 
    'justone', 
    'three3', 
    'duplicate', 
    'three3', 
    'three3', 
    'onlyone' 
);

$unique = array_unique($arr); 
$dupes = array_diff_key( $arr, $unique ); 
    // array( 5=>'duplicate', 6=>'three3' 7=>'three3' )

// count duplicates

array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
查看更多
登录 后发表回答