How to merge array and preserve keys?

How to merge array and preserve keys?

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

Stefan Bogdanescu

Founder & Senior Architect

Merging Arrays While Preserving Keys and Order: A Deep Dive into array_merge() vs. The Union Operator

When you need to combine two arrays in PHP, the default behavior often surprises developers. If you run $array1 (containing keys 'a', 'b', 'c') and $array2 (containing 'd' through 'f', plus a duplicate key 'a' and a numeric key '123'), your goal is to maintain the specific order of keys while allowing later values to overwrite earlier ones for matching string keys.

The standard array_merge() function fails here because it reindexes all keys that do not exist in the destination. When it encounters the duplicate key 'a', it keeps the value from $array2. However, when it hits the numeric key '123', it treats it as a non-associative entry and appends it at index 0, effectively stripping its original associative nature.

The union operator (+) offers an alternative but with different logic: it preserves keys from the left array that are also present in the right array, ignoring the right array's values for those duplicates. This is useful when you want to preserve the original value of 'a' from $array1, but it fails if your requirement is strictly about order preservation combined with overwriting logic based on appearance.

Swapping the operands ($array2 + $array1) fixes the overwriting issue but breaks the required sequence, placing keys from $array1 at the end regardless of their original position.

The Core Constraint: Why Built-ins Fail

The fundamental limitation arises from how PHP handles mixed arrays. array_merge() treats numeric keys as indices and string keys as names, but it cannot distinguish between a numeric key that is meant to be an associative identifier versus one that should be treated as an index. In your specific case, the key '123' is a string. While array_merge preserves string keys, its internal logic for ordering assumes that if a key exists in the second array but not the first, it should simply be appended. However, the resulting output shows [0] => 456, indicating that somewhere in the process, the numeric key handling interfered or the example provided implies a scenario where array_merge is stripping the '123' string nature and re-indexing.

Wait, looking closely at the source material's array_merge output:

Array
(
    [a] => 'new value'
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [0] => 456
)

The key '123' has disappeared and been replaced by index 0. This happens because array_merge normalizes keys. If the first array had an integer key, subsequent arrays are indexed starting from that number plus one. But here, both arrays appear to be associative (string keys). The issue in the source material's array_merge output suggests a specific version quirk or a misunderstanding of how array_merge handles mixed types, but typically array_merge preserves string keys unless they collide with existing integer keys in the first array.

However, assuming the source material is accurate that array_merge converts '123' to 0, this implies an internal re-indexing occurred. Regardless, the takeaway is clear: standard built-ins are designed for either pure merging (reindexing) or pure union (ignoring duplicates), not a hybrid "merge with overwrite and strict order" operation.

The High-Performance Solution: A Single Loop

You asked if there is a way to achieve this without writing a loop. The short answer is no, not natively in PHP's core array functions for mixed associative arrays. Both array_merge and the union operator are optimized C-level operations that make assumptions about key types. To enforce a strict "first seen" order while allowing later values to overwrite earlier ones (for string keys), you must iterate over the combined set of keys exactly once.

Performance-wise, a simple foreach loop in PHP 7.4+ is extremely fast and often outperforms complex multi-step function chaining that might involve array creation and re-indexing. The overhead of a manual loop is negligible compared to the logic required to reconstruct the order from scratch.

Implementation Strategy

To solve this, we need to construct the result array by iterating through both arrays in sequence. We maintain a pointer for the current key index if we were dealing with integers, but since we want to preserve string keys like 'a' and '123', we simply iterate over the keys of $array1 then $array2.

Here is the logic:

  1. Initialize an empty result array.
  2. Iterate through the keys of $array1, assigning them to the result. This preserves their order.
  3. Iterate through the keys of $array2, assigning them to the result. Since we are overwriting, if a key exists in both, the value from $array2 takes precedence.
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456];

$result = [];

// Iterate first array to preserve initial order
foreach ($array1 as $key => $value) {
    $result[$key] = $value;
}

// Iterate second array to add new keys and overwrite existing ones
foreach ($array2 as $key => $value) {
    $result[$key] = $value;
}

print_r($result);

This approach guarantees the output matches your requirement: 'a' becomes 'new value', all original keys remain in order, and '123' retains its string identity.

Trade-offs and Pitfalls

The primary trade-off here is explicit control versus implicit convenience. Using built-in functions like array_merge or + is syntactically shorter but semantically brittle when dealing with mixed key types. If your data structure relies heavily on associative keys, relying on the union operator might silently drop data you intended to merge if you aren't aware of the overwrite behavior.

Another pitfall is performance on massive datasets. While a loop is $O(N)$, creating intermediate arrays or using multiple built-in functions can increase memory allocation time. The single-pass loop approach minimizes memory churn. However, if you are dealing with millions of elements, the overhead of the PHP interpreter in the loop becomes significant compared to pure C implementations. In such extreme cases, you might consider writing a custom extension or using a specialized library, but for standard application logic, this loop is the most reliable and readable solution.

If you are working within a Laravel ecosystem, you might encounter similar needs when merging request attributes or configuration files. While Laravel provides helper functions, they often wrap these same underlying PHP behaviors. Understanding the core mechanics ensures you don't hit unexpected edge cases when building complex data transformations.

Our network