PHP
Merging PHP Arrays while Preserving Numeric Keys or Overwriting
Understand the key differences between `array_merge()` and the `+` operator for combining PHP arrays, especially when dealing with numeric and string keys.
<?php
$array1 = ['a' => 1, 'b' => 2, 0 => 'red', 1 => 'green'];
$array2 = ['c' => 3, 'a' => 4, 0 => 'blue', 2 => 'yellow'];
// Using array_merge():
// String keys from array2 overwrite array1.
// Numeric keys are re-indexed (new elements are appended).
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
/* Output:
Array
(
[a] => 4
[b] => 2
[0] => red
[1] => green
[2] => blue
[3] => yellow
)
*/
// Using the + operator (Union):
// String keys from array1 are preserved if they exist (array2 values are ignored).
// Numeric keys from array1 are preserved; array2 elements with *new* numeric keys are added.
$unionArray = $array1 + $array2;
print_r($unionArray);
/* Output:
Array
(
[a] => 1
[b] => 2
[0] => red
[1] => green
[2] => yellow
)
*/
$configDefault = ['host' => 'localhost', 'port' => 3306, 'user' => 'root'];
$configUser = ['port' => 8080, 'password' => 'secret'];
// Prioritize user config for overwrites, default for new keys
$finalConfig = array_merge($configDefault, $configUser);
print_r($finalConfig);
/* Output:
Array
(
[host] => localhost
[port] => 8080
[user] => root
[password] => secret
)
*/
// Alternatively, for config, the + operator from default to user config would prioritize default if keys exist:
$finalConfigUnion = $configDefault + $configUser;
print_r($finalConfigUnion);
/* Output:
Array
(
[host] => localhost
[port] => 3306
[user] => root
[password] => secret
)
*/
?>
How it works: In PHP, `array_merge()` and the `+` operator behave differently when combining arrays, especially regarding key handling. `array_merge()` re-indexes numeric keys starting from zero, while for string keys, values from the latter array overwrite those from the former. The `+` operator (array union) preserves existing keys from the first array; if a key exists in both, the value from the first array is kept, and only elements with non-existent keys from the second array are added. Understanding this distinction is crucial for correctly merging configuration settings, data sets, or any array where key preservation or overwriting logic is important.