PHP
Remove Duplicate Associative Arrays Based on a Specific Key Value
Efficiently filter an array of associative arrays to remove duplicates, ensuring each item is unique based on the value of a chosen key, cleaning up your data sets.
function removeDuplicatesByKey(array $array, string $key): array
{
$seenKeys = [];
$result = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$keyValue = $item[$key];
if (!in_array($keyValue, $seenKeys)) {
$seenKeys[] = $keyValue;
$result[] = $item;
}
} else {
// If the key is missing, decide whether to include it or not.
// For this example, we'll include it if no other item with a missing key was added (by reference, not robust).
// A more robust solution might handle missing keys differently (e.g., hash the whole item or skip).
$result[] = $item;
}
}
return $result;
}
$items = [
['id' => 1, 'name' => 'Apple'],
['id' => 2, 'name' => 'Banana'],
['id' => 1, 'name' => 'Apple'], // Duplicate ID
['id' => 3, 'name' => 'Orange'],
['id' => 2, 'name' => 'Grape'], // Duplicate ID, different name
];
$unique_items = removeDuplicatesByKey($items, 'id');
// var_dump($unique_items);
/* Expected Output:
[
["id" => 1, "name" => "Apple"],
["id" => 2, "name" => "Banana"],
["id" => 3, "name" => "Orange"]
]
*/
How it works: The `removeDuplicatesByKey` function processes an array of associative arrays to ensure uniqueness based on a specified key. It maintains a `$seenKeys` array to track encountered values for the given key. For each item in the input array, if its `$key`'s value hasn't been seen before, the item is added to the `$result` array and its key value is recorded. This ensures that only the first occurrence of an item with a given key value is kept, effectively filtering out duplicates.