PHP

Remove Duplicates from PHP Associative Arrays by Key

Efficiently remove duplicate entries from an array of associative arrays in PHP, ensuring uniqueness based on the value of a specific identifier key.

function removeDuplicatesByKey(array $array, string $uniqueKey): array
{
    $seenKeys = [];
    $uniqueArray = [];
    foreach ($array as $item) {
        if (isset($item[$uniqueKey]) && !in_array($item[$uniqueKey], $seenKeys)) {
            $seenKeys[] = $item[$uniqueKey];
            $uniqueArray[] = $item;
        }
    }
    return $uniqueArray;
}

$users = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 1, 'name' => 'Alice Smith'], // Duplicate ID
    ['id' => 3, 'name' => 'Charlie'],
    ['id' => 2, 'name' => 'Bobby'],     // Duplicate ID
];

$uniqueUsers = removeDuplicatesByKey($users, 'id');
/*
$uniqueUsers will be:
[
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie'],
]
*/
How it works: This snippet provides a function `removeDuplicatesByKey` that filters an array of associative arrays, keeping only the first occurrence of an item based on a specified unique key. It maintains a `$seenKeys` array to track the values of the unique key encountered so far. If an item's unique key value has not been seen before, the item is added to the `$uniqueArray` and its key value is recorded, ensuring uniqueness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs