PHP
Remove Duplicate Associative Array Elements Based on a Key
Efficiently filter out duplicate associative array elements in PHP by checking for uniqueness against a specified key's value, preserving the first occurrence.
<?php
function uniqueArrayOfAssociativeArrays(array $array, string $key): array {
$temp = [];
$result = [];
foreach ($array as $item) {
if (!isset($item[$key])) {
// Handle items without the specified key if necessary
continue;
}
if (!in_array($item[$key], $temp)) {
$temp[] = $item[$key];
$result[] = $item;
}
}
return $result;
}
$data = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 1, 'name' => 'Alicia'], // Duplicate 'id'
['id' => 3, 'name' => 'Charlie'],
['id' => 2, 'name' => 'Bobby'] // Duplicate 'id'
];
$uniqueData = uniqueArrayOfAssociativeArrays($data, 'id');
print_r($uniqueData);
/* Expected Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
)
[1] => Array
(
[id] => 2
[name] => Bob
)
[2] => Array
(
[id] => 3
[name] => Charlie
)
)
*/
?>
How it works: This snippet demonstrates how to remove duplicate associative array elements based on a specific key's value. The `uniqueArrayOfAssociativeArrays` function iterates through the input array. It uses a temporary array (`$temp`) to keep track of already seen key values. If an item's value for the specified key hasn't been encountered before, the item is added to the results, and its key value is recorded in `$temp`.