remove duplicates from comma separated string

前端 未结 5 1734
有刺的猬
有刺的猬 2021-01-13 07:06

Is there a better (faster) solution to remove duplicates from a comma separated string?

public function d($dep) { 
    if (strpos($dep,\',\') !== false) {
           


        
5条回答
  •  孤街浪徒
    2021-01-13 07:40

    You could use the uniqueness of array keys:

    function d($dep) {
        return implode(',', array_keys(array_flip(explode(',', $dep))));
    }
    

    array_flip swaps the key-value association, so the values become the keys and vice versa. This will automatically eliminate duplicates. Its runtime complexity is O(n).

提交回复
热议问题