PHP
Remove Duplicate Values and Re-index an Array
Learn to effortlessly remove duplicate values from a PHP array using `array_unique` and then re-index the resulting array numerically with `array_values` for cleaner data.
<?php
$data = [1, 2, 2, 3, 4, 4, 5, 'apple', 'banana', 'apple'];
// Remove duplicate values, preserving original keys
$uniqueData = array_unique($data);
// Result (keys preserved): [0 => 1, 1 => 2, 3 => 3, 4 => 4, 6 => 5, 7 => 'apple', 8 => 'banana']
// Remove duplicates and re-index the array numerically
$uniqueDataReindexed = array_values($uniqueData);
// Result (numerically re-indexed): [1, 2, 3, 4, 5, 'apple', 'banana']
$products = [
['id' => 1, 'name' => 'Shirt'],
['id' => 2, 'name' => 'Pants'],
['id' => 1, 'name' => 'Shirt'], // Duplicate based on content
['id' => 3, 'name' => 'Socks'],
];
// array_unique does not work directly on arrays of arrays without serialization
// To find unique arrays based on their content, you need a custom approach
$uniqueProducts = [];
$serializedProducts = [];
foreach ($products as $product) {
$serialized = serialize($product);
if (!in_array($serialized, $serializedProducts)) {
$serializedProducts[] = $serialized;
$uniqueProducts[] = $product;
}
}
// Result: [['id' => 1, 'name' => 'Shirt'], ['id' => 2, 'name' => 'Pants'], ['id' => 3, 'name' => 'Socks']]
echo "Unique Data (keys preserved): " . json_encode($uniqueData) . "
";
echo "Unique Data (re-indexed): " . json_encode($uniqueDataReindexed) . "
";
echo "Unique Products (custom): " . json_encode($uniqueProducts, JSON_PRETTY_PRINT) . "
";
?>
How it works: The `array_unique()` function removes duplicate values from an array, returning a new array with only the unique elements. It preserves the keys of the first occurrence of each value. If a numerically indexed array is desired after removing duplicates, `array_values()` can be chained to re-index the array sequentially starting from zero. For arrays of arrays or objects, `array_unique` won't work directly, requiring a custom serialization approach to identify unique nested structures.