PHP

Removing Duplicate Associative Arrays by a Specific Key

Discover how to efficiently remove duplicate associative arrays from a list based on a unique identifying key in PHP, keeping only the first occurrence.

<?php

function uniqueAssociativeArrayByKey(array $array, string $key): array {
    $seenKeys = [];
    $result = [];
    foreach ($array as $item) {
        if (isset($item[$key]) && !in_array($item[$key], $seenKeys, true)) {
            $seenKeys[] = $item[$key];
            $result[] = $item;
        }
    }
    return $result;
}

$students = [
    ['id' => 101, 'name' => 'Alice', 'grade' => 'A'],
    ['id' => 102, 'name' => 'Bob', 'grade' => 'B'],
    ['id' => 101, 'name' => 'Alice', 'grade' => 'A+'], // Duplicate ID
    ['id' => 103, 'name' => 'Charlie', 'grade' => 'C'],
    ['id' => 102, 'name' => 'Bob', 'grade' => 'B+'] // Duplicate ID
];

$uniqueStudents = uniqueAssociativeArrayByKey($students, 'id');
/*
$uniqueStudents will be:
[
    ['id' => 101, 'name' => 'Alice', 'grade' => 'A'],
    ['id' => 102, 'name' => 'Bob', 'grade' => 'B'],
    ['id' => 103, 'name' => 'Charlie', 'grade' => 'C']
]
*/

?>
How it works: This function iterates through an array of associative arrays. It uses an auxiliary array, `$seenKeys`, to keep track of the values of the specified `$key` that have already been encountered. If an item's key value has not been seen before, it's added to `$seenKeys` and the item itself is added to the `$result` array. This ensures that only the first occurrence of each unique key value is retained.

Need help integrating this into your project?

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

Hire DigitalCodeLabs