如何从PHP数组中删除重复值?


当前回答

$a = array(1, 2, 3, 4); 
$b = array(1, 6, 5, 2, 9); 
$c = array_merge($a, $b);
$unique = array_keys(array_flip($c));
print_r($unique);

其他回答

$result = array();
foreach ($array as $key => $value){
  if(!in_array($value, $result))
    $result[$key]=$value;
}
//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 )

使用array_unique()。

例子:

$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)

这是一个很好的方法。可能要确保它的输出又回到一个数组。现在只显示最后一个唯一值。

试试这个:

$arrDuplicate = array ("","",1,3,"",5);

foreach (array_unique($arrDuplicate) as $v){
  if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);

有多种方法可以做到这一点,如下所示

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

//second method
$array = array_unique($arr, SORT_REGULAR);