PHP

Remove Duplicates from Associative Arrays by Specific Key

Implement a PHP function to filter out duplicate associative arrays based on the value of a designated key, ensuring uniqueness in your datasets.

<?php
/**
 * Removes duplicate associative arrays from a list based on the value of a specific key.
 * The first occurrence of an item with a unique key value is kept.
 *
 * @param array $array The array of associative arrays to process.
 * @param string $key The key whose values determine uniqueness.
 * @return array The array with duplicates removed.
 */
function array_unique_by_key(array $array, string $key): array
{
    $seenKeys = [];
    $uniqueArray = [];

    foreach ($array as $item) {
        if (isset($item[$key])) {
            $keyValue = $item[$key];
            if (!in_array($keyValue, $seenKeys)) {
                $uniqueArray[] = $item;
                $seenKeys[] = $keyValue;
            }
        } else {
            // Optionally, handle items that don't have the specified key.
            // For this example, we'll just skip them, or you could add them if no key is present
            // $uniqueArray[] = $item;
        }
    }

    return $uniqueArray;
}

// Example usage:
$users = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 1, 'name' => 'Alicia', 'email' => '[email protected]'], // Duplicate ID and email
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bobby', 'email' => '[email protected]'] // Duplicate ID and email
];

echo "Unique users by ID:
";
$uniqueUsersById = array_unique_by_key($users, 'id');
print_r($uniqueUsersById);
/* Output:
Unique users by ID:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [email] => [email protected]
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
            [email] => [email protected]
        )

    [2] => Array
        (
            [id] => 3
            [name] => Charlie
            [email] => [email protected]
        )

)
*/

echo "
Unique users by email:
";
$uniqueUsersByEmail = array_unique_by_key($users, 'email');
print_r($uniqueUsersByEmail);
/* Output:
Unique users by email:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [email] => [email protected]
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
            [email] => [email protected]
        )

    [2] => Array
        (
            [id] => 3
            [name] => Charlie
            [email] => [email protected]
        )

)
*/
?>
How it works: This snippet provides a function `array_unique_by_key` to remove duplicate associative arrays from a list, where 'duplicate' is defined by the value of a specific key within each associative array. It iterates through the input array, keeping track of the key values it has already encountered. If an item's specified key value hasn't been seen before, the item is added to the result array, and its key value is marked as seen. This is highly useful for cleaning data, ensuring that you only process unique entities based on a chosen identifier like an 'id' or 'email' field, even if other fields differ.

Need help integrating this into your project?

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

Hire DigitalCodeLabs