PHP
Merge Multiple PHP Arrays Without Overwriting Scalars
Combine several PHP arrays, preserving all values, especially when merging keys with scalar values by creating nested arrays instead of overwriting.
<?php
$array1 = [
'id' => 101,
'name' => 'Product A',
'features' => ['color' => 'red', 'size' => 'M']
];
$array2 = [
'name' => 'Product B',
'price' => 29.99,
'features' => ['material' => 'cotton']
];
$array3 = [
'name' => 'Product C',
'price' => 35.50,
'features' => ['color' => 'blue'],
'tags' => ['new', 'sale']
];
// Merge using array_merge_recursive()
$mergedArray = array_merge_recursive($array1, $array2, $array3);
print_r($mergedArray);
/* Output:
Array
(
[id] => 101
[name] => Array
(
[0] => Product A
[1] => Product B
[2] => Product C
)
[features] => Array
(
[color] => Array
(
[0] => red
[1] => blue
)
[size] => M
[material] => cotton
)
[price] => Array
(
[0] => 29.99
[1] => 35.5
)
[tags] => Array
(
[0] => new
[1] => sale
)
)
*/
?>
How it works: The `array_merge_recursive()` function merges the elements of one or more arrays such that if an array key is found in more than one array, and both values are arrays, it merges the arrays recursively. If an array key contains a scalar value (non-array) in an earlier array and an array value in a later array, it converts the scalar to an array and merges it with the array value. If both values are scalars, it creates a new array containing both scalar values. This prevents data loss for conflicting scalar keys, unlike `array_merge()` which would overwrite.