PHP
Removing Duplicates from Associative Arrays by Key
Deduplicate an array of associative arrays in PHP by a chosen key, ensuring uniqueness for records based on a specific identifier while preserving other data for each unique entry.
<?php
function uniqueAssociativeArrayByKey(array $array, string $key): array
{
$seenKeys = [];
$result = [];
foreach ($array as $item) {
if (isset($item[$key]) && !in_array($item[$key], $seenKeys)) {
$seenKeys[] = $item[$key];
$result[] = $item;
}
}
return $result;
}
$users = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 1, 'name' => 'Alicia', 'email' => '[email protected]'], // Duplicate 'id'
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Robert', 'email' => '[email protected]'] // Duplicate 'id'
];
$uniqueUsers = uniqueAssociativeArrayByKey($users, 'id');
print_r($uniqueUsers);
/*
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[email] => [email protected]
)
[1] => Array
(
[id] => 2
[name] => Bob
[email] => [email protected]
)
[2] => Array
(
[id] => 3
[name] => Charlie
[email] => [email protected]
)
)
*/
?>
How it works: This `uniqueAssociativeArrayByKey` function filters an array of associative arrays to keep only unique entries based on a specified key. It maintains a `$seenKeys` array to track which key values have already been encountered. For each item, it checks if the value of the target key has been seen before; if not, the item is added to the result array and its key value is marked as seen, ensuring only the first occurrence of an item with a specific key value is kept.