PHP

Remove Duplicate Associative Arrays by Specific Key

Discover how to efficiently eliminate duplicate entries from a PHP array of associative arrays, ensuring uniqueness based on the value of a chosen identifier key.

$items = [
    ['id' => 1, 'name' => 'Pen', 'color' => 'Blue'],
    ['id' => 2, 'name' => 'Book', 'color' => 'Red'],
    ['id' => 1, 'name' => 'Pen', 'color' => 'Black'], // Duplicate ID
    ['id' => 3, 'name' => 'Notebook', 'color' => 'Green'],
    ['id' => 2, 'name' => 'Book', 'color' => 'Yellow'] // Duplicate ID
];

$uniqueItems = array_reduce($items, function($accumulator, $currentItem) {
    $id = $currentItem['id'];
    // If the ID is not already in the accumulator, add the item
    if (!isset($accumulator[$id])) {
        $accumulator[$id] = $currentItem;
    }
    return $accumulator;
}, []);

// Re-index the array if sequential keys are desired
$uniqueItems = array_values($uniqueItems);

print_r($uniqueItems);
/*
Expected output:
Array
(
    [0] => Array ( [id] => 1 [name] => Pen [color] => Blue )
    [1] => Array ( [id] => 2 [name] => Book [color] => Red )
    [2] => Array ( [id] => 3 [name] => Notebook [color] => Green )
)
*/
How it works: This snippet demonstrates how to remove duplicate associative arrays based on a specific key's value (e.g., 'id'). It uses `array_reduce` to iterate through the array. For each item, it uses the specified key's value as a key in an accumulating array. If an item with that key has not been added yet, it's added. This effectively keeps only the first occurrence of an item with a given ID. Finally, `array_values` is used to re-index the array with sequential numeric keys.

Need help integrating this into your project?

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

Hire DigitalCodeLabs