How to Remove Duplicates From a Comma Separated String in PHP?

Quick tips on how to remove duplicate values from a comma separate string in PHP

For all examples in this article, let's suppose we have the following comma separated string, which we want to remove duplicate values from:

$str = 'foo,bar,foo,baz';

Using array_unique()

We can remove duplicates from a string in the following three steps:

  1. Convert comma separated string to an array;
  2. Use array_unique() to remove duplicates;
  3. Convert the array back to a comma separated string.
$uniqueStr = implode(',', array_unique(explode(',', $str)));

echo $uniqueStr; // output: 'foo,bar,baz'

Both explode() and implode() in this case would have a runtime complexity of O(n). array_unique(), however, would have the runtime complexity of O(n log n) since it first sorts the array and then does a linear scanning. Following the rules of Big O, we drop O(n) and keep the most dominant term O(n log n) as it has a much heavier impact on performance. This gives us an overall runtime complexity of O(n log n). That being said, this method is more readable as it is immediately clear from reading the code what we're trying to do.

Using array_flip() and array_keys()

Since array keys are unique in PHP, if we flip the array key/value associations, duplicates would be removed automatically. We can achieve this in the following steps:

  1. Convert comma separated string to an array;
  2. Use array_flip() to swap key/value association. In doing so duplicates are automatically discarded;
  3. Use array_keys() to create an array with keys as values;
  4. Convert the array back to a comma separated string.
$uniqueStr = implode(',', array_keys(array_flip(explode(',', $str))));

echo $uniqueStr; // output: 'foo,bar,baz'

array_flip(), array_keys(), explode() and implode() all have a time complexity of O(n) in this case. Therefore, the overall runtime complexity of using this method would be O(n). That being said, this method is not very readable as it may not immediately be clear from reading the code what we're trying to do.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.