Array Functions

PHP array_replace_recursive() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_replace_recursive() function replaces the values in an array with the values from other arrays recursively. This function is mainly used with deeper arrays (an array inside an array).

The following table summarizes the technical details of this function.

Return Value: Returns the replaced array, or NULL if an error occurs.
Version: PHP 5.3.0+

Syntax

The basic syntax of the array_replace_recursive() function is given with:

array_replace_recursive(array1, array2, ...)

The following example shows the array_replace_recursive() function in action.

<?php
// Sample arrays
$array1 = array("pets"=>array("cat"), "wilds"=>array("wolf", "fox"));
$array2 = array("pets"=>array("dog", "horse"), "wilds"=>array("tiger"));

// Performing array replacement recursively
$result = array_replace_recursive($array1, $array2);
print_r($result);
?>

The array_replace_recursive() function replaces the values of the first array with the values from the following arrays in such a way that, if a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not in the first, it will be created in the first array. If a key only exists in the first array, it will be left as is.

If multiple arrays are passed for the replacement, they will be processed in order, the later arrays overwriting the previous values. And, since this function is recursive, it will recurse into arrays and apply the same process to the inner values. See more examples at the bottom.


Parameters

The array_replace_recursive() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array in which elements are replaced.
array2 Optional. Specifies the array from which elements will be extracted.
... Optional. Specifies more array from which elements will be extracted. Values from later arrays overwrite the previous values.

More Examples

Here're some more examples showing how array_replace_recursive() function basically works:

The following example shows what happens if several arrays are passed for replacement.

<?php
// Sample arrays
$array1 = array("pets"=>array("cat"), "wilds"=>array("wolf", "fox"));
$array2 = array("pets"=>array("dog", "horse"), "wilds"=>array("tiger"));
$array3 = array("pets"=>array("rabbit"), "wilds"=>array("lion"));

// Performing array replacement recursively
$result = array_replace_recursive($array1, $array2, $array3);
print_r($result);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties