PHP

Remove Duplicates from Associative Arrays by a Unique Key

Efficiently eliminate redundant entries from an array of associative arrays, keeping only the first occurrence based on a designated unique identifier key.

function uniqueByKey(array $array, string $key): array {
    $uniqueItems = [];
    $seenKeys = [];

    foreach ($array as $item) {
        if (isset($item[$key]) && !in_array($item[$key], $seenKeys)) {
            $uniqueItems[] = $item;
            $seenKeys[] = $item[$key];
        }
    }
    return $uniqueItems;
}

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

$uniqueUsers = uniqueByKey($users, 'id');
print_r($uniqueUsers);
How it works: The `uniqueByKey` function processes an array of associative arrays to remove duplicates based on the value of a specific key. It iterates through the input array, maintaining a `$seenKeys` array to track key values encountered so far. If an item's specified key value has not been seen before, the item is added to the `$uniqueItems` array, and its key value is recorded, ensuring that only the first occurrence of each unique key value is preserved in the output.

Need help integrating this into your project?

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

Hire DigitalCodeLabs