Using PHP's array_replace_recursive() Function to Recursively Merge Arrays
This article explains PHP's array_replace_recursive() function, detailing its syntax, recursive merging behavior, example usage with code, output interpretation, important considerations, and compares it with array_merge_recursive() for effective backend array handling in PHP development.
PHP is a popular web programming language that provides a rich set of functions, including array_replace_recursive() , which can recursively merge two or more arrays by combining their keys, values, and sub‑arrays.
The basic syntax of the function is:
array_replace_recursive(array1, array2, array3......);The function accepts multiple arrays as arguments and returns a new array that results from recursively merging the input arrays. When keys match, their values are merged; if a value is itself an array, the merge continues recursively until no nested arrays remain.
Example usage:
$array1 = array(
'fruit' => array(
'apple' => 1,
'orange' => 4,
'banana' => 3
),
'vegetable' => array(
'potato' => 2,
'broccoli' => 1,
'carrot' => 4
)
);
$array2 = array(
'fruit' => array(
'orange' => 2
),
'vegetable' => array(
'potato' => 3,
'broccoli' => 2,
'carrot' => 1
)
);
$result = array_replace_recursive($array1, $array2);
print_r($result);The output of the above code is:
Array
(
[fruit] => Array
(
[apple] => 1
[orange] => 2
[banana] => 3
)
[vegetable] => Array
(
[potato] => 3
[broccoli] => 2
[carrot] => 1
)
)As shown, the values from $array2 recursively overwrite the corresponding keys in $array1 , while keys that do not appear in the later arrays remain unchanged.
When using array_replace_recursive() , if the same key appears in multiple arrays, the later array's value overrides the earlier one. Keys must be strings or integers; otherwise a warning is generated.
If you need to keep existing keys and values while adding new ones from another array, you can use array_merge_recursive() . Unlike array_replace_recursive() , the merge function preserves both values for duplicate keys, creating nested arrays instead of overwriting.
In summary, array_replace_recursive() is a practical function for recursively merging arrays in PHP, allowing precise control over which keys are overwritten or retained, making it valuable for backend development tasks that involve complex array manipulation.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.