PHP
Remove Duplicate Values from an Array
Learn to quickly eliminate duplicate values from a PHP array using `array_unique`, with options to preserve or reset numeric and string keys effectively.
<?php
$numbers = [1, 2, 2, 3, 4, 4, 5, 1];
// Remove duplicates, preserving the key of the first occurrence
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);
/* Output:
Array
(
[0] => 1
[1] => 2
[3] => 3
[4] => 4
[6] => 5
)
*/
// If you want keys to be reset (re-indexed from 0):
$reindexedUniqueNumbers = array_values(array_unique($numbers));
print_r($reindexedUniqueNumbers);
/* Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
*/
$colors = ['red', 'green', 'blue', 'red', 'yellow', 'BLUE'];
// array_unique is case-sensitive by default
$uniqueColors = array_unique($colors);
print_r($uniqueColors);
/* Output:
Array
(
[0] => red
[1] => green
[2] => blue
[4] => yellow
[5] => BLUE
)
*/
How it works: The `array_unique()` function in PHP removes duplicate values from an array. By default, it preserves the original key for the first occurrence of each unique value. If you need a zero-indexed array after removing duplicates, you can wrap the result in `array_values()`. It's important to note that `array_unique()` performs a case-sensitive comparison for string values, so 'blue' and 'BLUE' are treated as distinct values.