views:

242

answers:

1

Hello,

I am looking for the fastest way to remove duplicate values in a string separated by commas.

So my string looks like this;

$str = 'one,two,one,five,seven,bag,tea';

I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?

+11  A: 

The shortest code would be:

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

If it is the fastest... I don't know, it is probably faster then looping explicitly.

Reference: implode, array_unique, explode

Felix Kling
Thank you @Felix, that is excellent, that is what I needed, the max values in a string are 50.
Adnan
@Adnan: With 50 values this should not be much of a problem :)
Felix Kling