PHP

Remove Duplicate Associative Array Elements by Key

Learn to filter an array of associative arrays, removing duplicates based on the value of a chosen key, ensuring unique entries in your dataset.

function unique_multidimensional_array($array, $key): array
{
    $temp_array = [];
    $i = 0;
    $key_array = [];

    foreach ($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return array_values($temp_array); // Re-index the array
}

$users = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 1, 'name' => 'Alice'], // Duplicate ID and name
    ['id' => 3, 'name' => 'Charlie'],
    ['id' => 2, 'name' => 'Robert'], // Duplicate ID, different name
];

$uniqueUsersById = unique_multidimensional_array($users, 'id');

// $uniqueUsersById will be:
// [
//     ['id' => 1, 'name' => 'Alice'],
//     ['id' => 2, 'name' => 'Bob'],
//     ['id' => 3, 'name' => 'Charlie']
// ]
How it works: This function filters an array of associative arrays, keeping only unique entries based on a specified key. It iterates through the array, maintaining a list of seen key values. If a key's value hasn't been encountered before, the entire associative array is added to the result. Finally, `array_values` re-indexes the resulting array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs