PHP
Extract Unique Values from an Array
Learn how to easily remove duplicate values from a PHP array using array_unique, creating a new array with only distinct elements, improving data integrity.
<?php
$colors = ['red', 'green', 'blue', 'red', 'yellow', 'green'];
// Get unique values, preserving the first encountered key
$uniqueColors = array_unique($colors);
echo "Original Colors:
";
print_r($colors);
echo "
Unique Colors (keys preserved):
";
print_r($uniqueColors);
$numbers = [1, 2, 3, 2, 1, 4, 5, 4];
// Get unique values and re-index the array
$uniqueNumbersReindexed = array_values(array_unique($numbers));
echo "
Original Numbers:
";
print_r($numbers);
echo "
Unique Numbers (re-indexed):
";
print_r($uniqueNumbersReindexed);
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 1, 'name' => 'Alice'], // Duplicate
['id' => 3, 'name' => 'Charlie'],
['id' => 2, 'name' => 'Bob'] // Duplicate
];
// Get unique associative arrays based on a specific key (e.g., 'id')
// A more complex example, often done by looping or using array_reduce
$uniqueUsersById = array_reduce($users, function ($carry, $item) {
$found = false;
foreach ($carry as $existingItem) {
if ($existingItem['id'] === $item['id']) {
$found = true;
break;
}
}
if (!$found) {
$carry[] = $item;
}
return $carry;
}, []);
echo "
Unique Users by ID:
";
print_r($uniqueUsersById);
?>
How it works: The array_unique() function removes duplicate values from an array, returning a new array with only the unique elements. By default, it preserves the key of the first encountered value. To get a re-indexed array, array_values() can be used on the result. For unique associative arrays based on specific keys within nested arrays, a manual iteration or array_reduce with custom logic is often required to define what constitutes a unique entry.