Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicates from comma separated string

Tags:

php

csv

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

public function d($dep) { 
    if (strpos($dep,',') !== false) {
        $nd = explode(',',$dep);
        $oa = array_unique($nd);
        $nx = (count($oa) > 1) ? implode(",",$oa) : $oa[0];
    }
    else {
        $nx = $dep;
    }

    return $nx;
}

Thanks guys.

like image 967
Jeremy Roy Avatar asked Feb 27 '11 15:02

Jeremy Roy


2 Answers

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

like image 123
Gumbo Avatar answered Oct 07 '22 18:10

Gumbo


Try just this:

$uniqueDep = implode(',', array_unique(explode(',', $dep)));
like image 38
erisco Avatar answered Oct 07 '22 17:10

erisco