PHP

Combine PHP Arrays: `array_merge` vs. `+` Operator

Understand the differences between `array_merge()` and the `+` operator in PHP for combining arrays, crucial for correctly handling numerical and string keys.

<?php
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 10, 'd' => 20, 'e' => 30];

// Using array_merge(): numerical keys are re-indexed, string keys overwrite
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
/* Expected output:
Array
(
    [a] => 1
    [b] => 10
    [c] => 3
    [d] => 20
    [e] => 30
)
*/

// Using + operator: string keys from the first array are preserved, numerical keys are appended
$combinedArray = $array1 + $array2;
print_r($combinedArray);
/* Expected output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [d] => 20
    [e] => 30
)
*/

// Example with numerical keys
$numArray1 = [1, 2, 3]; // Keys are 0, 1, 2
$numArray2 = [4, 5, 6]; // Keys are 0, 1, 2

$mergedNumArray = array_merge($numArray1, $numArray2);
print_r($mergedNumArray); // Expected output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

$combinedNumArray = $numArray1 + $numArray2;
print_r($combinedNumArray); // Expected output: Array ( [0] => 1 [1] => 2 [2] => 3 )
?>
How it works: This snippet highlights the distinct behaviors of `array_merge()` and the `+` operator when combining arrays in PHP. `array_merge()` appends elements, overwriting values for duplicate string keys from the later array, and re-indexing numerical keys. The `+` operator, however, performs a union: it adds elements from the second array only if their keys (both string and numerical) do not already exist in the first array, effectively preserving the values from the first array for duplicate keys. Understanding this difference is crucial for predictable array manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs