PHP
Merge PHP Arrays: Understanding `array_merge` vs. `+` Operator
Explore two primary methods for combining PHP arrays: array_merge() for re-indexing numeric keys and concatenating, and the + operator for appending with key preservation.
<?php
// Case 1: Indexed arrays - array_merge re-indexes
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$mergedIndexed = array_merge($array1, $array2);
print_r($mergedIndexed); // Result: [1, 2, 3, 4, 5, 6]
// Case 2: Associative arrays - array_merge overwrites duplicate string keys
$assoc1 = ['a' => 1, 'b' => 2];
$assoc2 = ['b' => 3, 'c' => 4];
$mergedAssoc = array_merge($assoc1, $assoc2);
print_r($mergedAssoc); // Result: ['a' => 1, 'b' => 3, 'c' => 4]
// Case 3: Associative arrays - '+' operator preserves keys from the first array
$plusAssoc = $assoc1 + $assoc2;
print_r($plusAssoc); // Result: ['a' => 1, 'b' => 2, 'c' => 4]
// Case 4: Mixed keys with array_merge - numeric keys are re-indexed, string keys overwrite
$mixed1 = [0 => 'apple', 'color' => 'red'];
$mixed2 = [0 => 'banana', 'size' => 'large'];
$mergedMixed = array_merge($mixed1, $mixed2);
print_r($mergedMixed); // Result: ['apple', 'red', 'banana', 'large']
?>
How it works: PHP offers two main ways to combine arrays: array_merge() and the + operator. array_merge() concatenates arrays; for numerically indexed arrays, it re-indexes the keys. For associative arrays, if a string key exists in both arrays, the value from the latter array overwrites the former. The + operator, however, behaves differently: it appends elements from the second array to the first, but only if the keys from the second array do not already exist in the first array, effectively preserving the first array's values for any duplicate keys.