PHP
Merging PHP Arrays with Different Strategies for Duplicate Keys
Explore various methods for merging PHP arrays, understanding how `array_merge()`, the `+` operator, and `array_replace()` handle duplicate string and numeric keys differently for robust data management.
<?php
$array1 = ["a" => 1, "b" => 2, 0 => "apple", 1 => "banana"];
$array2 = ["c" => 3, "a" => 4, 0 => "orange", 1 => "grape"];
echo "Array 1:
";
print_r($array1);
echo "Array 2:
";
print_r($array2);
// 1. Using array_merge(): numeric keys are re-indexed, string keys overwrite
$mergedArray = array_merge($array1, $array2);
echo "
Using array_merge(): (string keys overwrite, numeric keys re-indexed)
";
print_r($mergedArray);
// 2. Using the '+' operator: string keys from first array are preserved, numeric keys from first array are preserved
$plusOperatorResult = $array1 + $array2;
echo "
Using '+' operator: (string/numeric keys from first array preserved on conflict)
";
print_r($plusOperatorResult);
// 3. Using array_replace(): string and numeric keys from second array overwrite
$replacedArray = array_replace($array1, $array2);
echo "
Using array_replace(): (string/numeric keys from second array overwrite)
";
print_r($replacedArray);
// Example with only numeric keys for clarity
$numArray1 = [1, 2, 3];
$numArray2 = [4, 5, 6];
$numArray3 = [0 => 10, 1 => 20];
echo "
Numeric Array 1: "; print_r($numArray1);
echo "Numeric Array 2: "; print_r($numArray2);
echo "Numeric Array 3: "; print_r($numArray3);
echo "
array_merge(numArray1, numArray2): "; print_r(array_merge($numArray1, $numArray2));
echo "+ operator (numArray1 + numArray2): "; print_r($numArray1 + $numArray2);
echo "array_replace(numArray1, numArray3): "; print_r(array_replace($numArray1, $numArray3));
?>
How it works: Merging arrays in PHP can be done in several ways, each with distinct behavior regarding duplicate keys. `array_merge()` appends arrays, re-indexing numeric keys and overwriting string keys. The `+` operator, when used for array union, preserves the values from the *first* array for conflicting string or numeric keys. `array_replace()` overwrites existing keys (both numeric and string) in the first array with values from subsequent arrays, adding new keys if they don't exist.