PHP

Merging Arrays (Preserving Numeric Keys vs. Overwriting)

Learn how to combine multiple PHP arrays using array_merge to re-index numeric keys and the '+' operator to preserve numeric keys while overwriting string keys.

<?php
$numericArray1 = [0 => 'apple', 1 => 'banana'];
$numericArray2 = [1 => 'grape', 2 => 'orange'];
$stringArray1 = ['a' => 1, 'b' => 2];
$stringArray2 = ['b' => 3, 'c' => 4];

// array_merge(): Re-indexes numeric keys, appends new elements, last value wins for string keys
$resultMergeNumeric = array_merge($numericArray1, $numericArray2);
// Result: ['apple', 'banana', 'grape', 'orange']

$resultMergeString = array_merge($stringArray1, $stringArray2);
// Result: ['a' => 1, 'b' => 3, 'c' => 4]

// '+' operator: Preserves numeric keys from the first array, first value wins for string keys
$resultPlusNumeric = $numericArray1 + $numericArray2;
// Result: [0 => 'apple', 1 => 'banana', 2 => 'orange']

$resultPlusString = $stringArray1 + $stringArray2;
// Result: ['a' => 1, 'b' => 2, 'c' => 4]

echo "array_merge (numeric keys):
";
print_r($resultMergeNumeric);
echo "
array_merge (string keys):
";
print_r($resultMergeString);
echo "
'+' operator (numeric keys):
";
print_r($resultPlusNumeric);
echo "
'+' operator (string keys):
";
print_r($resultPlusString);
?>
How it works: This snippet demonstrates the distinct behaviors of `array_merge()` and the `+` operator when combining arrays in PHP. `array_merge()` re-indexes numeric keys, appending values and overwriting string keys if they exist in subsequent arrays. In contrast, the `+` operator preserves numeric keys from the left-hand array and only adds key-value pairs from the right-hand array if their keys do not already exist in the left-hand array, including for string keys. Choose `array_merge()` when you need a simple append and re-indexing of numeric values, and the `+` operator when you want to prioritize the keys from the first array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs