Jeremy Roy
Jeremy Roy

Reputation: 1291

remove duplicates from comma separated string

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.

Upvotes: 6

Views: 19109

Answers (5)

user2873260
user2873260

Reputation:

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

Upvotes: 0

Jeremy Roy
Jeremy Roy

Reputation: 1291

Many many thanks guys. Finally, we have two solutions (Pascal and Ericso gave the same solution) here and the question became which one is faster. To be honest, by faster, I meant what executes faster and if I take words of Gumbo, I get the combined functions of array_keys and array_flip is faster than array_unique. Because, the two other functions, implode and explode are same.

return implode(',', array_unique(explode(',', $dep)));
return implode(',', array_keys(array_flip(explode(',', $dep))));

Finally I gave 1 up to all three ad many thanks that can't be measured / seen. I agree that either of the three solutions can be expected, but then took the answer of Gumbo believing that array_keys(array_flip()) is faster to execute than array_unique() in the given context.

Cheers.

Upvotes: 2

Gumbo
Gumbo

Reputation: 655319

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

Upvotes: 25

Pascal MARTIN
Pascal MARTIN

Reputation: 401032

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

Upvotes: 5

erisco
erisco

Reputation: 14329

Try just this:

$uniqueDep = implode(',', array_unique(explode(',', $dep)));

Upvotes: 18

Related Questions