Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/2613063/remove-duplicate-from-string-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...