PHP

Merging and Removing Duplicates from Arrays

Learn various techniques to efficiently merge multiple PHP arrays while simultaneously removing duplicate values to obtain a unique combined set.

// Scenario 1: Merging two simple indexed arrays and removing duplicates
$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];
$mergedUnique1 = array_unique(array_merge($array1, $array2));
// $mergedUnique1 will be [1, 2, 3, 4, 5, 6] (keys are re-indexed numerically)

// Scenario 2: Merging associative arrays - simple values, preserving keys where possible
$settings1 = ['theme' => 'dark', 'font_size' => 'medium'];
$settings2 = ['font_size' => 'large', 'language' => 'en'];
$mergedSettings = array_merge($settings1, $settings2);
// $mergedSettings will be ['theme' => 'dark', 'font_size' => 'large', 'language' => 'en']
// Note: 'font_size' from $settings2 overwrites $settings1.

// Scenario 3: Merging associative arrays, preserving values and removing duplicates based on value
// For distinct values regardless of original key, array_unique on values.
$tags1 = ['php', 'javascript', 'html'];
$tags2 = ['css', 'javascript', 'php', 'react'];
$combinedTags = array_values(array_unique(array_merge($tags1, $tags2)));
// $combinedTags will be ['php', 'javascript', 'html', 'css', 'react'] (numeric keys)

// Scenario 4: Merging arrays of associative arrays and removing duplicates based on a specific key
// (e.g., merging user lists, ensuring each user appears only once by their 'id')
function mergeUniqueById(array $arr1, array $arr2, string $idKey = 'id'): array {
    $combined = array_merge($arr1, $arr2);
    $uniqueItems = [];
    $seenIds = [];
    foreach ($combined as $item) {
        if (isset($item[$idKey]) && !in_array($item[$idKey], $seenIds)) {
            $uniqueItems[] = $item;
            $seenIds[] = $item[$idKey];
        } else if (!isset($item[$idKey])) {
            // Handle items without an ID key or unique identifier, or skip
            $uniqueItems[] = $item;
        }
    }
    return $uniqueItems;
}

$users1 = [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']];
$users2 = [['id' => 2, 'name' => 'Bobby'], ['id' => 3, 'name' => 'Charlie']];
$mergedUsers = mergeUniqueById($users1, $users2, 'id');
/*
// $mergedUsers will be [
//     ['id' => 1, 'name' => 'Alice'], 
//     ['id' => 2, 'name' => 'Bob'], 
//     ['id' => 3, 'name' => 'Charlie']
// ]
// Note: 'Bob' is kept from $users1, 'Bobby' from $users2 is ignored as ID 2 already seen.
*/
How it works: This snippet demonstrates several ways to merge PHP arrays and handle duplicates. `array_merge` combines arrays, with later values overwriting earlier ones for identical string keys. `array_unique` removes duplicate scalar values from indexed arrays. For associative arrays, custom logic is often needed to define what constitutes a 'duplicate,' such as using a specific key (like an ID) to ensure uniqueness, as shown in the `mergeUniqueById` function.

Need help integrating this into your project?

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

Hire DigitalCodeLabs