PHP

Remove Duplicate Associative Arrays by Specific Key in PHP

Filter out duplicate associative arrays from a list based on the value of a chosen key. Useful for ensuring unique records in data sets from APIs or databases.

<?php
function unique_associative_array_by_key(array $array, string $key): array
{
    $seenKeys = [];
    $uniqueArray = [];
    foreach ($array as $item) {
        if (isset($item[$key]) && !in_array($item[$key], $seenKeys)) {
            $uniqueArray[] = $item;
            $seenKeys[] = $item[$key];
        }
    }
    return $uniqueArray;
}

$data = [
    ['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Bob', 'city' => 'London'],
    ['id' => 1, 'name' => 'Alicia', 'city' => 'Paris'], // Duplicate ID
    ['id' => 3, 'name' => 'Charlie', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Robert', 'city' => 'Berlin']  // Duplicate ID
];

// Remove duplicates based on 'id'
$uniqueById = unique_associative_array_by_key($data, 'id');
/*
$uniqueById will be:
[
    ['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Bob', 'city' => 'London'],
    ['id' => 3, 'name' => 'Charlie', 'city' => 'New York']
]
*/
print_r($uniqueById);

// Remove duplicates based on 'city'
$uniqueByCity = unique_associative_array_by_key($data, 'city');
/*
$uniqueByCity will be:
[
    ['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Bob', 'city' => 'London']
    // 'Paris' and 'Berlin' are unique, 'New York' (from Charlie) is skipped
]
*/
print_r($uniqueByCity);
?>
How it works: This `unique_associative_array_by_key` function filters an array of associative arrays, retaining only the first occurrence of each element based on a specified key's value. It maintains a list of 'seen' key values to prevent adding duplicates, effectively ensuring uniqueness for records that might share a common identifier or property.

Need help integrating this into your project?

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

Hire DigitalCodeLabs