PHP Program to Remove Duplicates from Array
array_unique(), for example: $uniqueArray = array_unique($array);.Examples
How to Think About It
array_unique() that does this automatically by scanning the array and removing repeated values, leaving only unique ones.Algorithm
Code
<?php $array = [1, 2, 2, 3, 4, 4, 5]; $uniqueArray = array_unique($array); print_r($uniqueArray); ?>
Dry Run
Let's trace the array [1, 2, 2, 3, 4, 4, 5] through the code.
Input array
The array is [1, 2, 2, 3, 4, 4, 5].
Apply array_unique
The function scans and removes repeated values, keeping only the first occurrence.
Resulting array
The resulting array is [1, 2, 3, 4, 5] with original keys preserved.
| Original Array | After array_unique |
|---|---|
| [1, 2, 2, 3, 4, 4, 5] | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Using array_unique
The array_unique() function scans the array and removes duplicate values, keeping only the first occurrence.
Step 2: Preserving keys
This function preserves the original keys of the first occurrences, which can be useful if keys matter.
Step 3: Output with print_r
Using print_r() shows the array structure clearly, including keys and values.
Alternative Approaches
<?php $array = [1, 2, 2, 3, 4, 4, 5]; $uniqueArray = []; foreach ($array as $value) { if (!in_array($value, $uniqueArray)) { $uniqueArray[] = $value; } } print_r($uniqueArray); ?>
<?php $array = [1, 2, 2, 3, 4, 4, 5]; $uniqueArray = array_keys(array_flip($array)); print_r($uniqueArray); ?>
Complexity: O(n) time, O(n) space
Time Complexity
The function scans each element once, so the time grows linearly with the array size.
Space Complexity
It creates a new array to store unique values, so extra space grows with the number of unique elements.
Which Approach is Fastest?
array_unique() is the fastest and simplest built-in method; manual loops are slower and more code.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array_unique() | O(n) | O(n) | Quick and easy removal of duplicates |
| Manual loop with in_array() | O(n^2) | O(n) | Learning logic but slower for large arrays |
| array_flip twice | O(n) | O(n) | Removes duplicates but resets keys |
array_unique() for a quick and easy way to remove duplicates from arrays in PHP.array_unique() preserves keys, which can cause unexpected keys in the result.