PHP Program to Remove Duplicates from String
implode('', array_unique(str_split($string))) in PHP to remove duplicate characters from a string by splitting it, filtering unique characters, and joining them back.Examples
How to Think About It
Algorithm
Code
<?php $string = "programming"; $unique = implode('', array_unique(str_split($string))); echo $unique; ?>
Dry Run
Let's trace the string 'programming' through the code to remove duplicates.
Input string
$string = 'programming'
Split into characters
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
Remove duplicates
['p', 'r', 'o', 'g', 'a', 'm', 'i', 'n']
Join characters
'progamin'
| Index | Character | Unique Array After Step |
|---|---|---|
| 0 | p | ['p'] |
| 1 | r | ['p', 'r'] |
| 2 | o | ['p', 'r', 'o'] |
| 3 | g | ['p', 'r', 'o', 'g'] |
| 4 | r | ['p', 'r', 'o', 'g'] |
| 5 | a | ['p', 'r', 'o', 'g', 'a'] |
| 6 | m | ['p', 'r', 'o', 'g', 'a', 'm'] |
| 7 | m | ['p', 'r', 'o', 'g', 'a', 'm'] |
| 8 | i | ['p', 'r', 'o', 'g', 'a', 'm', 'i'] |
| 9 | n | ['p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'] |
| 10 | g | ['p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'] |
Why This Works
Step 1: Split string into characters
Using str_split() breaks the string into an array of single characters so we can work with each one.
Step 2: Remove duplicates
The array_unique() function keeps only the first occurrence of each character, removing duplicates.
Step 3: Join characters back
Finally, implode('') joins the unique characters back into a single string without spaces.
Alternative Approaches
<?php $string = "programming"; $result = ''; for ($i = 0; $i < strlen($string); $i++) { if (strpos($result, $string[$i]) === false) { $result .= $string[$i]; } } echo $result; ?>
<?php $string = "programming"; $result = preg_replace_callback('/(.)\\1+/', function($m) { return $m[1]; }, $string); echo $result; ?>
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and filtering unique characters each take linear time relative to the string length, so overall time is O(n).
Space Complexity
Extra space is needed to store the array of characters and the unique array, so space complexity is O(n).
Which Approach is Fastest?
Using array_unique with str_split is concise and efficient; manual loops are slower but more flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array_unique + str_split | O(n) | O(n) | Quick and simple duplicate removal |
| Manual loop with strpos | O(n^2) | O(n) | Understanding logic, small strings |
| Regex for consecutive duplicates | O(n) | O(n) | Removing only consecutive duplicates |
array_unique(str_split($string)) to quickly remove duplicate characters from a string in PHP.