Merge two numerically-keyed associative arrays and preserve the original keys

Merge two numerically-keyed associative arrays and preserve the original keys

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

Stefan Bogdanescu

Founder & Senior Architect

Merging Numerically-Keyed Arrays Without Losing Keys

When working with associative arrays in PHP, specifically those containing string representations of numbers as keys (e.g., '11', '22'), developers often encounter a subtle pitfall when attempting to merge them. The standard approach using array_merge() followed by array_unique() fails because array_merge reindexes numeric keys starting from zero, discarding the original keys entirely. Even if you use array_unique, it operates on values by default unless told otherwise, and without proper handling, it won't guarantee the preservation of the specific string keys you started with.

To achieve a merge that retains all unique keys while respecting their original string format, you must bypass the automatic reindexing behavior of array_merge. The most robust solution involves constructing a new array where the keys are explicitly defined before assigning values. This ensures that if two arrays share a key like '44', the value from the second array overwrites the first (or vice versa), but the key itself remains '44' rather than becoming an integer 0.

Here is a direct implementation using a loop to build the result:

$array1 = [
    '11' => '11',
    '22' => '22',
    '33' => '33',
    '44' => '44',
];

$array2 = [
    '44' => '44',
    '55' => '55',
    '66' => '66',
    '77' => '77',
];

$result = [];

foreach ($array1 as $key => $value) {
    $result[$key] = $value;
}

foreach ($array2 as $key => $value) {
    // Explicitly set the key. 
    // If the key exists, it overwrites the previous entry (standard merge behavior).
    $result[$key] = $value;
}

// Debug output to verify keys are preserved
print_r($result);

This approach manually iterates through both arrays, adding elements to a fresh container. Because we are assigning values to $result[$key], PHP treats the key as a string identifier rather than an index for sequential access. This preserves the '11', '22', etc., exactly as they appear in the source data.

Handling Duplicates and Order

The logic above inherently handles duplicates by allowing later assignments to overwrite earlier ones. In your specific example, both arrays contain '44' => '44'. Since the values are identical, the result is unchanged visually, but the key structure remains intact. If the values differed (e.g., $array1['44'] was 'A' and $array2['44'] was 'B'), this method would keep '44' => 'B'.

If your requirement is strictly to remove duplicates based on value and ensure only one entry exists per key, you might need an additional check. However, in PHP, the definition of "duplicate" in associative arrays usually refers to the key itself. You cannot have two entries with the same key; one must overwrite the other. If you intended to filter by value uniqueness across different keys (which doesn't apply here since your values match keys), that would be a different problem requiring array_filter or additional logic.

The Laravel Approach

If you are working within the Laravel ecosystem, this pattern is frequently encountered when merging configuration data from different sources or handling session payloads. While you can write the loop directly, Laravel provides helper methods that wrap this logic cleanly.

The merge() method on a collection or config array handles key preservation similarly, but for raw arrays, sticking to the explicit iteration ensures predictability. In many cases, developers might reach for Arr::except or Arr::only in combination with merge, but for this specific task of simply concatenating two numerically-keyed arrays without reindexing, the manual assignment loop is the most transparent and performant solution.

There are scenarios where you might prefer array_replace (available since PHP 5.3) instead of a manual loop. It performs exactly this operation: it takes an array and replaces its elements with those from a second array, preserving keys.

$result = array_replace($array1, $array2);

array_replace is functionally equivalent to the manual loop shown earlier but offers better readability. It guarantees that the resulting array contains only unique keys derived from the input arrays, maintaining their string format regardless of whether they were originally numeric or string indices. This utility function is particularly useful when cleaning up data structures where order and key integrity are paramount.

Ultimately, the choice between a manual loop and array_replace depends on your PHP version and code style preferences, but both successfully avoid the automatic reindexing trap that plagues array_merge. By explicitly managing key assignment, you ensure your data structure remains consistent with its intended schema.

Our network