PHP
Remove Duplicate Values from PHP Arrays
Discover how to effectively remove duplicate values from a PHP array using `array_unique()`, maintaining original keys or re-indexing for clean and unique data sets.
<?php
$data = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana'];
$dataWithKeys = ['a' => 'red', 'b' => 'blue', 'c' => 'red', 'd' => 'green'];
// Remove duplicates, re-index numeric keys
$uniqueValues = array_unique($data);
print_r($uniqueValues);
// Remove duplicates, preserve associative keys
$uniqueValuesWithKeys = array_unique($dataWithKeys);
print_r($uniqueValuesWithKeys);
// To get unique values and re-index all keys:
// $reindexedUniqueValues = array_values(array_unique($dataWithKeys));
// print_r($reindexedUniqueValues);
?>
How it works: The `array_unique()` function is used here to filter out all duplicate values from an array. When applied to a numerically indexed array, it re-indexes the array. For associative arrays, it preserves the key of the first occurrence of each unique value. Combining it with `array_values()` can force a complete re-indexing if desired.