PHP
Merging Multiple Arrays (Understanding Numeric Key Handling)
Learn to effectively combine multiple arrays in PHP using `array_merge()` and understand its key differences from the `+` operator, especially concerning numeric and string keys.
<?php
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];
// Using array_merge() - re-indexes numeric keys and overwrites associative keys from right to left
$mergedArrayMerge = array_merge($array1, $array2, $array3);
// $mergedArrayMerge will be [1, 2, 3, 4, 5, 6, 7, 8, 9]
$assoc1 = ['a' => 1, 'b' => 2];
$assoc2 = ['c' => 3, 'a' => 4];
$mergedAssocMerge = array_merge($assoc1, $assoc2);
// $mergedAssocMerge will be ['a' => 4, 'b' => 2, 'c' => 3]
// Using the '+' operator - preserves numeric keys (discarding elements with duplicate numeric keys from right-hand array)
// For associative arrays, the left-hand array's values are preserved for duplicate string keys
$mergedPlus = $array1 + $array2 + $array3;
// $mergedPlus will be [1, 2, 3] if $array2 and $array3 have same numeric keys, as first encountered keys are kept.
$mergedAssocPlus = $assoc1 + $assoc2;
// $mergedAssocPlus will be ['a' => 1, 'b' => 2, 'c' => 3]
echo "Merged with array_merge (numeric): " . print_r($mergedArrayMerge, true) . "
";
echo "Merged with array_merge (associative): " . print_r($mergedAssocMerge, true) . "
";
echo "Merged with + operator (numeric - caution): " . print_r($mergedPlus, true) . "
";
echo "Merged with + operator (associative): " . print_r($mergedAssocPlus, true) . "
";
?>
How it works: This snippet demonstrates merging arrays using `array_merge()` and the `+` operator. `array_merge()` re-indexes numeric keys sequentially and overwrites duplicate associative keys with values from later arrays. In contrast, the `+` operator preserves numeric keys (keeping the leftmost value for duplicate keys) and maintains the leftmost value for duplicate associative keys. Understanding these distinct behaviors is crucial for predictable array merging.