Back to blog
PHPOctober 23, 2011

Merging PHP Arrays While Preserving Indexes

A concise technique for merging PHP arrays without resetting their original index keys.


Merging arrays is a frequent operation in PHP, but the built-in array_merge() function has two behaviors that can be problematic:


1. It reindexes numeric keys starting from 0

2. It may reorder entries in the process


The Solution: The Union Operator


PHP's + operator merges arrays while preserving the original keys:


$array1 = [0 => 'apple', 1 => 'banana'];

$array2 = [3 => 'cherry', 5 => 'date'];


// array_merge resets indexes

$merged = array_merge($array1, $array2);

// Result: [0 => 'apple', 1 => 'banana', 2 => 'cherry', 3 => 'date']


// Union operator preserves indexes

$merged = $array1 + $array2;

// Result: [0 => 'apple', 1 => 'banana', 3 => 'cherry', 5 => 'date']


The behavior is straightforward: keys from both arrays are preserved, and when duplicate keys exist, the value from the left-hand array takes precedence.


This is a simple but powerful technique that is especially useful when working with associative data where index preservation is critical.