remove duplicates from comma separated string

前端 未结 5 1797
有刺的猬
有刺的猬 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:55

    I would probably use the same kind of idea that what you posted ; but I think you can remove your two conditions, to use only this :

    $exploded = explode(',', $str);
    $unique = array_unique($exploded);
    $imploded = implode(',', $unique);
    var_dump($imploded);
    

    I've tested it with those three strings, and it seems to work in each case :

    $str = 'a,b,c,d,a,c,e,f';
    $str = 'a,a';
    $str = 'a';
    


    Notes :

    • Using explode on a string that doesn't contain the delimiter will return an array with one element -- your test with strpos is not necessary.
    • And using implode on an array with only one element will work too (not adding any delimiter) -- your test with the ternary operator is not necessary either.


    Of course, you can also remove the variables, and use only one line :

    $result = implode(',', array_unique(explode(',', $str)));
    

    Not sure it's easier to understand that way, though...

提交回复
热议问题