PHP
Merging PHP Arrays: `array_merge` vs `+` Operator
Understand the key differences between PHP's `array_merge()` function and the array `+` operator when combining arrays, especially how they handle duplicate numeric and string keys.
<?php
$array1 = ['a', 'b', 'c'];
$array2 = ['d', 'e', 'f'];
// Using array_merge() for numerically indexed arrays
// Appends new elements, re-indexing if needed
$mergedNumeric = array_merge($array1, $array2);
// Result: ['a', 'b', 'c', 'd', 'e', 'f']
// Using + operator for numerically indexed arrays
// Keeps existing keys from the first array, ignores duplicates from the second
$plusNumeric = $array1 + $array2;
// Result: ['a', 'b', 'c'] (keys 0, 1, 2 already exist in $array1)
$assoc1 = ['name' => 'John', 'age' => 30];
$assoc2 = ['age' => 31, 'city' => 'New York'];
$assoc3 = ['occupation' => 'Developer'];
// Using array_merge() for associative arrays
// Overwrites values with the same string key from subsequent arrays
$mergedAssoc = array_merge($assoc1, $assoc2, $assoc3);
// Result: ['name' => 'John', 'age' => 31, 'city' => 'New York', 'occupation' => 'Developer']
// Using + operator for associative arrays
// Adds elements from the second array only if the key does not already exist in the first array
$plusAssoc = $assoc1 + $assoc2 + $assoc3;
// Result: ['name' => 'John', 'age' => 30, 'city' => 'New York', 'occupation' => 'Developer']
echo "Merged Numeric (array_merge): " . json_encode($mergedNumeric) . "
";
echo "Plus Numeric (+ operator): " . json_encode($plusNumeric) . "
";
echo "Merged Associative (array_merge): " . json_encode($mergedAssoc) . "
";
echo "Plus Associative (+ operator): " . json_encode($plusAssoc) . "
";
?>
How it works: This snippet demonstrates two ways to combine arrays in PHP: `array_merge()` and the `+` operator. `array_merge()` re-indexes numeric arrays and overwrites associative values with identical string keys from later arrays. The `+` operator, however, adds elements from the right-hand array only if their keys (numeric or string) do not already exist in the left-hand array, preserving the initial array's key-value pairs.