PHP
Merge PHP Arrays with Key Preservation or Overwriting
Understand how to combine PHP arrays using array_merge() for numeric re-indexing and the '+' operator for key-preserving merges in specific associative array scenarios.
<?php
$array1 = [1, 2, 'a' => 'apple'];
$array2 = [3, 4, 'b' => 'banana', 'a' => 'avocado'];
// Using array_merge(): re-indexes numeric keys, overwrites string keys
$mergedArrayMerge = array_merge($array1, $array2);
// Using '+' operator: numeric keys are untouched, string keys from the left array are preserved
$mergedPlusOperator = $array1 + $array2;
$array3 = ['item1', 'item2'];
$array4 = ['item3', 'item4'];
$mergedNumeric = $array3 + $array4; // Numeric keys are preserved from left array
echo "Using array_merge():
";
print_r($mergedArrayMerge);
echo "Using '+' operator (associative):
";
print_r($mergedPlusOperator);
echo "Using '+' operator (numeric):
";
print_r($mergedNumeric);
?>
How it works: When merging arrays, array_merge() re-indexes numeric keys starting from zero and overwrites string keys if they exist in subsequent arrays. The '+' operator, however, behaves differently: it only adds key-value pairs from the right-hand array if the key does not already exist in the left-hand array. This means for duplicate string keys, the value from the first array is preserved, and numeric keys from the left array are also preserved if they clash. This makes them suitable for different merging strategies.