PHP
Remove Duplicate Associative Arrays by a Unique Key
Learn to filter an array of associative arrays, removing duplicates where a specific key's value (e.g., 'id') is identical, keeping only the first occurrence.
<?php
$users = [
['id' => 101, 'name' => 'Alice'],
['id' => 102, 'name' => 'Bob'],
['id' => 101, 'name' => 'Alice Smith'], // Duplicate ID
['id' => 103, 'name' => 'Charlie'],
['id' => 102, 'name' => 'Robert'] // Duplicate ID
];
function removeDuplicatesByKey(array $array, string $key): array
{
$seenKeys = [];
$uniqueArray = [];
foreach ($array as $item) {
if (!isset($item[$key])) {
// Handle items without the specified key, or add them if desired
continue;
}
if (!in_array($item[$key], $seenKeys)) {
$seenKeys[] = $item[$key];
$uniqueArray[] = $item;
}
}
return $uniqueArray;
}
$uniqueUsers = removeDuplicatesByKey($users, 'id');
print_r($uniqueUsers);
// Alternative using array_column and array_unique for simpler cases or when you want to re-index:
// $uniqueUsers = array_values(array_intersect_key($users, array_unique(array_column($users, 'id'))));
?>
How it works: The `removeDuplicatesByKey` function iterates through the input array. It maintains a `$seenKeys` array to track values of the specified unique key (`'id'` in this example) that have already been encountered. If an item's key value is not yet in `$seenKeys`, the item is added to `$uniqueArray`, and its key value is recorded. This ensures only the first occurrence of each unique key value is kept, effectively removing duplicates.