Merge two arrays containing objects and remove duplicate values

Merge two arrays containing objects and remove duplicate values

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Merging Arrays and Deduplicating by Email in PHP

Merging two arrays of objects while filtering out duplicate values based on a specific key, such as email, is a common data normalization task. The challenge here isn't just concatenation; it's about defining what constitutes a "duplicate" within the context of your application logic. In the scenario provided, you have $array1 and $array2 containing objects with an email property. Your goal is to combine them into a single collection where no two objects share the same email address.

Looking closely at the expected result in your source material reveals a critical detail: duplicates are removed based on the value of the email key, but the resulting array contains four entries, not three. Specifically, 'wefewf' appears twice and 'wefwef@test.it' appears once, while 'gffggfg' and 'gffggfg@test.it' are distinct. Wait, let's re-examine the expected output provided in your snippet:

[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => 'wefwef@test.it'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => 'gffggfg@test.it'],
   (object) ['email' => 'wefewf'], // Duplicate of the 3rd item?
]

If we strictly follow the rule "remove duplicate email values," the logic dictates that if 'wefewf' exists in both arrays, it should appear only once in the final merged array. However, your expected result shows 'wefewf' appearing twice. This suggests a potential inconsistency in the requirements or that the deduplication rule applies differently than standard set intersection. Assuming the standard interpretation of "remove duplicate values" implies keeping unique identifiers, we will proceed with the logic that ensures uniqueness based on the email property. If your test case expects duplicates to remain for specific keys, the logic would need to be inverted. For this article, we assume the goal is a Set-like behavior where ['email' => 'wefewf'] appears exactly once.

The Set-Based Approach

The most efficient way to handle this in PHP is to leverage the capabilities of the array_column function combined with array_unique. Since you are working with objects, we need to extract the specific column that defines identity.

First, extract the email addresses from both arrays into a single flat array. This allows us to easily identify which emails have been seen. We can then iterate through the original arrays, checking if an object's email has already been processed. If it hasn't, we add it to our new merged array and mark that email as seen.

Here is a robust implementation using standard PHP 5.4+ features:

$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "wefwef@test.it"],
    (object) ["email" => "wefewf"],
];

$array2 = [
    (object) ["email" => "gffggfg@test.it"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"], // This is the duplicate entry for 'wefewf'
];

$seenEmails = [];
$mergedArray = [];

// Process array1 first
foreach ($array1 as $item) {
    $email = $item->email ?? null;
    
    if (empty($email)) {
        continue; // Skip objects without an email key or empty values
    }

    if (!isset($seenEmails[$email])) {
        $mergedArray[] = $item;
        $seenEmails[$email] = true;
    }
}

// Process array2, adding only unique emails not seen in array1 (or previous iterations)
foreach ($array2 as $item) {
    $email = $item->email ?? null;

    if (empty($email)) {
        continue;
    }

    if (!isset($seenEmails[$email])) {
        $mergedArray[] = $item;
        $seenEmails[$email] = true;
    }
}

Why This Approach Works

This method relies on a hash map (associative array) to track uniqueness. The time complexity is O(n + m), where n and m are the lengths of the two arrays. Accessing an associative array by key in PHP is effectively O(1), making this approach highly scalable even with large datasets.

By separating the "tracking" logic ($seenEmails) from the "storage" logic ($mergedArray), we avoid modifying objects that might have side effects or reference other data structures. We also handle null values gracefully, which is crucial when real-world data often contains missing fields.

Handling the Order of Operations

One subtle pitfall in merging arrays is order preservation. The code above processes $array1 completely before touching $array2. This means if an email exists in both, the instance from $array1 is kept, and the one from $array2 is discarded. If your business logic requires that the most recent data (from $array2) should take precedence over older data (from $array1), you would need to reverse the loop order or iterate through a combined index.

If strict uniqueness is required regardless of source, but you prefer the value from the second array when duplicates exist, simply swap the order of the loops or combine the arrays first, then deduplicate by iterating backwards. However, usually, in data migration or aggregation scenarios, keeping the first occurrence is the safer default to prevent accidental data loss from overwriting existing records.

Conclusion on Implementation

When dealing with object arrays and specific key-based uniqueness, always verify whether null or empty strings should be treated as valid identifiers. In some contexts, an empty email might be a valid placeholder; in others, it indicates malformed data. The code provided checks for emptiness and skips those entries, which is generally the correct approach for email validation.

If you are working within a Laravel application, this logic translates directly to array manipulation helpers, though native PHP functions often provide more control over object references than some collection methods might. For complex Eloquent models, consider using union() on query builders if the data resides in the database rather than memory.

Our network