PHP

Removing Duplicate Values from Simple and Associative Arrays

Efficiently eliminate duplicate values from both numerically indexed and associative PHP arrays to ensure data uniqueness and integrity.

<?php

// Simple array with duplicates
$numbers = [1, 2, 3, 2, 4, 1, 5];
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);

echo "
---

";

// Associative array with duplicates (based on a specific key, e.g., 'email')
$users = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 3, 'name' => 'Alice', 'email' => '[email protected]'], // Duplicate email
    ['id' => 4, 'name' => 'Charlie', 'email' => '[email protected]'],
    ['id' => 5, 'name' => 'Bob', 'email' => '[email protected]'] // Duplicate email
];

$uniqueUsers = [];
$seenEmails = [];

foreach ($users as $user) {
    if (!in_array($user['email'], $seenEmails)) {
        $uniqueUsers[] = $user;
        $seenEmails[] = $user['email'];
    }
}

print_r($uniqueUsers);
How it works: This snippet illustrates two methods for duplicate removal. For simple numerically indexed arrays, `array_unique()` efficiently removes redundant values. For associative arrays where uniqueness is determined by a specific key (like 'email' in the example), a manual loop is used. It maintains a list of 'seen' keys and only adds an element to the result if its key value hasn't been encountered before, ensuring unique entries based on that criterion.

Need help integrating this into your project?

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

Hire DigitalCodeLabs