How to remove all instances of duplicated values from an array

前端 未结 9 1144
心在旅途
心在旅途 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;
    }
    

提交回复
热议问题