How to remove all instances of duplicated values from an array

前端 未结 9 1087
心在旅途
心在旅途 2021-01-02 19:48

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:

相关标签:
9条回答
  • 2021-01-02 19:59

    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;
    }
    
    0 讨论(0)
  • 2021-01-02 20:03

    You can use

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

    See

    • array_count_values — Counts all the values of an array
    • array_filter — Filters elements of an array using a callback function
    • array_keys — Return all the keys or a subset of the keys of an array
    • callbacks
    0 讨论(0)
  • 2021-01-02 20:09

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

    0 讨论(0)
  • 2021-01-02 20:12

    Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:

    function get_default($array)
    {
        $default = array_column($array, 'default', 'id');
        $array = array_diff($default, array_diff_assoc($default, array_unique($default)));
    
        return key($array);
    }
    

    In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it

    0 讨论(0)
  • 2021-01-02 20:14

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

    array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
    
    0 讨论(0)
  • 2021-01-02 20:18

    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.

    0 讨论(0)
提交回复
热议问题