How to remove all instances of duplicated values f

2020-02-28 15:50发布

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.

Example input:

banna, banna, mango, mango, apple

Expected output:

apple

标签: php arrays
9条回答
家丑人穷心不美
2楼-- · 2020-02-28 16:20

The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))

查看更多
叛逆
3楼-- · 2020-02-28 16:25

You can use

$singleOccurences = array_keys(
    array_filter(
        array_count_values(
            array('banana', 'mango', 'banana', 'mango', 'apple' )
        ),
        function($val) {
            return $val === 1;
        }
    )
)

See

查看更多
4楼-- · 2020-02-28 16:26

You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list? Hmm it does sound like something you'll need to roll your own.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-02-28 16:26

There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:

$count = array();
foreach ($values as $value) {
  if (array_key_exists($value, $count))
    ++$count[$value];
  else
    $count[$value] = 1;
}

$unique = array();
foreach ($count as $value => $count) {
  if ($count == 1)
    $unique[] = $value;
}
查看更多
▲ chillily
6楼-- · 2020-02-28 16:27

You can use a combination of array_unique, array_diff_assoc and array_diff:

array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
查看更多
欢心
7楼-- · 2020-02-28 16:32

Just write your own simple foreach loop:

$used = array();    
$array = array("banna","banna","mango","mango","apple");

foreach($array as $arrayKey => $arrayValue){
    if(isset($used[$arrayValue])){
        unset($array[$used[$arrayValue]]);
        unset($array[$arrayKey]);
    }
    $used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=>  string(5) "apple" } 

have fun :)

查看更多
登录 后发表回答