PHP - Merging two arrays into one array (also Remove Duplicates)

PHP - Merging two arrays into one array (also Remove Duplicates)

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

Stefan Bogdanescu

Founder & Senior Architect

Merging Arrays of stdClass Objects and Removing Duplicates in PHP

When working with data fetched from a database or an API, it is common to receive results as an array of stdClass objects. In your specific scenario, you have two arrays containing identical stdClass objects—specifically, both contain an entry with ID 749 and matching metadata like post_date. Using array_merge() on these structures results in a single flat array where the first object's keys are overwritten by the second, but the second object itself remains intact as a separate element. This creates a list that logically contains duplicates.

To solve this, you need to distinguish between merging scalar values and deduplicating objects based on their content. The naive approach of simply running array_unique() directly on an array of objects often fails in older PHP versions or returns unexpected results because object comparison relies on reference equality by default. If the two stdClass instances are different entities in memory holding the same data, array_unique will treat them as distinct unless you change how they are compared.

The most robust way to remove duplicates from an array of objects is to define a unique identity for each item before or during the merge process. In your example, the ID field serves as the perfect primary key. You can leverage this by converting the array of objects into an associative array where the keys are the IDs. This ensures that every object in the collection has a unique string identifier.

Here is how you can achieve the merge and deduplication in a single, efficient pass:

$merged = [];

foreach ($array1 as $obj) {
    // Convert the object to an associative array to handle keys easily
    $data = (array)$obj;
    
    // Use the ID as the key. If the ID doesn't exist yet, add the data.
    // This automatically prevents duplicates if the same ID appears again.
    $merged[$data['ID']] = $data; 
}

foreach ($array2 as $obj) {
    $data = (array)$obj;
    // Overwrite only if this specific ID hasn't been added yet, or merge depending on needs.
    // Since you want to remove duplicates, overwriting with the same data is safe.
    if (!isset($merged[$data['ID']])) {
        $merged[$data['ID']] = $data;
    }
}

// Convert back to an indexed array of objects if strictly required for downstream logic
$result = array_values(array_map(function($item) {
    return (object)$item;
}, $merged));

By using the ID as the associative array key, you ensure that even if both arrays contain the exact same object data, the second occurrence is ignored because the key already exists. This approach is significantly more performant than looping through the merged array and checking every field value against a previous entry. It reduces time complexity from linear scans of potentially large datasets to near-constant time lookups via hash tables.

If your objects do not have a reliable unique identifier like ID, you must construct a composite key or use a library like SplObjectHash (available in PHP 8.1+) to generate a hash based on the object's state. However, relying on an existing primary key is always preferable when designing data structures for merging.

In Laravel projects, this pattern is frequently encountered when handling Eloquent collections or paginated responses. If you are using the LaravelCompany ecosystem or similar frameworks, remember that their collection helpers often provide convenient methods like unique() which handle this deduplication logic internally, often by defaulting to a specific column if available. Always check the underlying data structure before assuming these helpers will work seamlessly on raw stdClass arrays without configuration.

The key takeaway is that array_merge is designed for scalar merging, not object deduplication. When dealing with complex objects, shifting your mental model from indexed lists to associative maps keyed by unique identifiers provides a cleaner, more efficient solution.

Our network