PHP

Remove Duplicate Associative Array Entries Based on a Specific Key

Efficiently deduplicate an array of associative arrays by ensuring uniqueness for a chosen key. Prevents redundant data entries in lists.

function uniqueArrayOfAssociativeArrays(array $array, string $key): array
{
    $seenKeys = [];
    $uniqueArray = [];

    foreach ($array as $item) {
        if (!isset($item[$key])) {
            // Handle items without the key, perhaps add them or skip
            $uniqueArray[] = $item;
            continue;
        }

        $keyValue = $item[$key];
        if (!in_array($keyValue, $seenKeys, true)) {
            $uniqueArray[] = $item;
            $seenKeys[] = $keyValue;
        }
    }

    return $uniqueArray;
}

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

$uniquePeople = uniqueArrayOfAssociativeArrays($people, 'id');
print_r($uniquePeople);
How it works: The `uniqueArrayOfAssociativeArrays` function processes an array of associative arrays to remove duplicates based on the value of a specified `$key`. It maintains a `$seenKeys` array to track the values of the target key that have already been encountered. If an item's `$key` value is not yet in `$seenKeys`, the entire item is added to the `$uniqueArray` and its key value is recorded. This ensures only the first occurrence of an item with a given key value is kept.

Need help integrating this into your project?

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

Hire DigitalCodeLabs