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:53

If you concern in performance and have simple array, use:

array_keys(array_flip($array));

It's many times faster than array_unique.

查看更多
余生无你
3楼-- · 2018-12-31 08:54
$result = array();
foreach ($array as $key => $value){
  if(!in_array($value, $result))
    $result[$key]=$value;
}
查看更多
还给你的自由
4楼-- · 2018-12-31 08:54

It can be done through function I made three function duplicate returns the values which are duplicate in array.

Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;

function duplicate($arr) {
    $duplicate;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] > 1) {
            $duplicate[$value] = $value;
        }
    }
    return $duplicate;
}
function single($arr) {
    $single;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] == 1) {
            $single[$value] = $value;
        }
    }
    return $single;
}
function full($arr, $arry) {
    $full = $arr + $arry;
    sort($full);
    return $full;
}
查看更多
初与友歌
5楼-- · 2018-12-31 08:55

explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));

This will take care of key associations and serialize the keys for the resulting new array :-)

查看更多
妖精总统
6楼-- · 2018-12-31 08:56

Remove duplicate values from an associative array in PHP.

$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );

foreach($arrDup as $k =>  $v){
  if(!( isset ($hold[$v])))
      $hold[$v]=1;
  else
      unset($arrDup[$k]);
}

Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )

查看更多
时光乱了年华
7楼-- · 2018-12-31 08:56

try this short & sweet code -

$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();

foreach($array as $v){
  isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
  }

var_dump($unique);

Output -

array(6) {
  [0]=>
  int(1)
  [1]=>
  int(4)
  [2]=>
  int(2)
  [3]=>
  int(7)
  [4]=>
  int(9)
  [5]=>
  int(5)
}
查看更多
登录 后发表回答