How to Implement PHP’s array_replace_recursive Without Using Built-In Functions
Introduction
The array_replace_recursive function in PHP is used to replace values in a multi-dimensional array recursively, with values from one or more arrays. But what if you need to achieve this without using the built-in function? This guide provides a step-by-step approach to implement array_replace_recursive manually using basic PHP constructs.
Why Avoid array_replace_recursive?
Avoiding built-in functions can be useful for:
- Gaining a deeper understanding of recursion and arrays.
- Tackling coding challenges where built-in functions are restricted.
- Customizing the functionality to meet unique requirements.
Manual Implementation of array_replace_recursive
Code Example
Here’s a custom implementation of array_replace_recursive:
function customArrayReplaceRecursive($array1, ...$arrays) {
// Ensure the first parameter is an array
if (!is_array($array1)) {
return [];
}
// Start with the base array
$result = $array1;
// Iterate through the additional arrays
foreach ($arrays as $array) {
if (is_array($array)) {
foreach ($array as $key => $value) {
// Check if the value is an array and the key exists in the base array
if (is_array($value) && isset($result[$key]) && is_array($result[$key])) {
// Recursive call for nested arrays
$result[$key] = customArrayReplaceRecursive($result[$key], $value);
} else {
// Replace or add the value from the current array
$result[$key] = $value;
}
}
}
}
return $result;
}
// Example usage
$array1 = [
"a" => ["x" => "apple", "y" => "banana"],
"b" => "cherry",
"c" => ["z" => "dragonfruit"]
];
$array2 = [
"a" => ["y" => "blueberry"],
"c" => ["z" => "elderberry", "w" => "fig"],
"d" => "grape"
];
$result = customArrayReplaceRecursive($array1, $array2);
print_r($result);
Output:
Array
(
[a] => Array
(
[x] => apple
[y] => blueberry
)
[b] => cherry
[c] => Array
(
[z] => elderberry
[w] => fig
)
[d] => grape
)
Explanation of the Code
- Input Validation: The function ensures the first argument is an array.
- Base Array Initialization: The $result starts as a copy of $array1.
- Recursive Replacement: If a value is an array and the corresponding key exists in $result, the function calls itself to handle nested arrays.
- Replace/Add Values: Non-array values are replaced or added directly.
- Final Output: The modified array, with replacements applied recursively, is returned.