PHP
Remove Duplicates While Preserving Original Keys (First Occurrence)
Learn to efficiently remove duplicate values from a PHP array, keeping the original key of the first instance for each unique value, without re-indexing.
function remove_duplicates_preserve_keys(array $array): array {
return array_reverse(array_flip(array_reverse($array)));
}
$data = [
'a' => 'apple',
'b' => 'banana',
'c' => 'apple',
'd' => 'orange',
'e' => 'banana',
'f' => 'grape'
];
$uniqueData = remove_duplicates_preserve_keys($data);
print_r($uniqueData);
/* Output:
Array
(
[a] => apple
[b] => banana
[d] => orange
[f] => grape
)*/
How it works: This clever snippet removes duplicate values from an array while preserving the original keys associated with the *first* occurrence of each unique value. It achieves this using a combination of `array_reverse` and `array_flip`. The first `array_reverse` places the last occurrences of values at the beginning. `array_flip` then uses these values as keys; since keys must be unique, duplicate values overwrite previous entries. Finally, `array_reverse` is called again to restore the original order, effectively keeping only the first occurrence of each value along with its original key.