PHP

Extract Unique Associative Array Elements by Key Value

Learn how to filter an array of associative arrays to keep only unique entries based on the value of a specified key, effectively removing duplicates.

<?php
function uniqueArrayByKey(array $array, string $key): array {
    $seenKeys = [];
    $uniqueArray = [];
    foreach ($array as $item) {
        if (is_array($item) && isset($item[$key])) {
            $keyValue = $item[$key];
            if (!in_array($keyValue, $seenKeys)) {
                $uniqueArray[] = $item;
                $seenKeys[] = $keyValue;
            }
        } else {
            // Handle non-associative items or items missing the key if necessary
            // For simplicity, this example just skips them or adds if not associative
            // If the item is not an array or missing the key, it won't be considered for uniqueness by key
            // You might add it directly or log a warning based on requirements
            $uniqueArray[] = $item; // Or skip if strict associative filtering is needed
        }
    }
    return $uniqueArray;
}

$users = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'], // Duplicate ID
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'], // Duplicate ID
    ['id' => 4, 'name' => 'David', 'email' => '[email protected]'],
];

$uniqueById = uniqueArrayByKey($users, 'id');
/*
Output (first occurrence of each ID is kept):
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]
        )

    [3] => Array
        (
            [id] => 4
            [name] => David
            [email] => [email protected]
        )

)
*/
print_r($uniqueById);
?>
How it works: This `uniqueArrayByKey` function filters an array of associative arrays, retaining only the first occurrence of an item based on the unique value of a specified key. It iterates through the array, tracking `seenKeys`. If an item's key value hasn't been encountered before, the item is added to the `uniqueArray` and its key value is recorded. This is highly useful for de-duplicating data sets where uniqueness is determined by a specific field like an 'id' or 'email'.

Need help integrating this into your project?

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

Hire DigitalCodeLabs