PHP
Merging Arrays: array_merge() vs. + Operator
Understand the key differences between PHP's `array_merge()` function and the array union (`+`) operator when combining arrays, especially with duplicate keys and indexing.
<?php
$array1 = [1, 2, 'a' => 'apple', 'b' => 'banana'];
$array2 = [3, 4, 'a' => 'apricot', 'c' => 'cherry'];
echo "--- Using array_merge() ---
";
// array_merge re-indexes numeric keys and overwrites associative keys
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
echo "
--- Using + (Union) Operator ---
";
// Union operator preserves keys from the first array if duplicates exist
$unionArray = $array1 + $array2;
print_r($unionArray);
$array3 = ['a', 'b'];
$array4 = ['c', 'd'];
echo "
--- Numeric keys with array_merge() ---
";
$mergedNumeric = array_merge($array3, $array4);
print_r($mergedNumeric); // [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'] - re-indexed
echo "
--- Numeric keys with + (Union) Operator ---
";
$unionNumeric = $array3 + $array4;
print_r($unionNumeric); // [0 => 'a', 1 => 'b'] - only keys from first array if they overlap (0, 1)
?>
How it works: In PHP, `array_merge()` and the `+` (union) operator behave differently when merging arrays, especially concerning duplicate keys. `array_merge()` appends elements, re-indexing numeric keys and overwriting associative keys with values from the later array. Conversely, the `+` operator performs a union, preserving all keys from the first array if a key exists in both (including numeric keys), effectively 'ignoring' duplicate keys from the second array. Understanding these differences is crucial for predictable array merging behavior.