The array_replace_recursive() function in PHP is used to recursively replace elements of the first array with values from subsequent arrays. It goes deeper into the nested structure of arrays and replaces values based on their key hierarchy.
array_replace_recursive(array $array1, array ...$arrays): array
$array1 = [
'a' => ['apple', 'banana'],
'b' => ['orange', 'grape']
];
$array2 = [
'a' => ['mango'],
'b' => ['peach']
];
$result = array_replace_recursive($array1, $array2);
print_r($result);
Output:
Array
(
[a] => Array
(
[0] => mango
[1] => banana
)
[b] => Array
(
[0] => peach
[1] => grape
)
)
$array1 = [
'person' => [
'name' => 'Alice',
'age' => 25
],
'address' => [
'city' => 'New York',
'state' => 'NY'
]
];
$array2 = [
'person' => [
'name' => 'Bob'
],
'address' => [
'state' => 'CA'
]
];
$result = array_replace_recursive($array1, $array2);
print_r($result);
Output:
Array
(
[person] => Array
(
[name] => Bob
[age] => 25
)
[address] => Array
(
[city] => New York
[state] => CA
)
)
$array1 = [
'fruits' => ['apple', 'banana'],
'vegetables' => ['carrot', 'pepper']
];
$array2 = [
'fruits' => ['mango'],
'vegetables' => ['spinach']
];
$result = array_replace_recursive($array1, $array2);
print_r($result);
Output:
Array
(
[fruits] => Array
(
[0] => mango
[1] => banana
)
[vegetables] => Array
(
[0] => spinach
[1] => pepper
)
)
$array1 = [
'company' => [
'name' => 'TechCorp',
'location' => [
'city' => 'Los Angeles',
'state' => 'CA'
]
]
];
$array2 = [
'company' => [
'location' => [
'city' => 'San Francisco'
]
]
];
$result = array_replace_recursive($array1, $array2);
print_r($result);
Output:
Array
(
[company] => Array
(
[name] => TechCorp
[location] => Array
(
[city] => San Francisco
[state] => CA
)
)
)
The array_replace_recursive() function allows you to merge multidimensional arrays by replacing elements in a hierarchical manner. This function is incredibly useful when dealing with complex data structures, especially when you need to overwrite specific elements of nested arrays without losing other parts of the data. It's an efficient way to handle configuration arrays or data manipulation where nested replacements are required.