array_replace_recursive()
array_replace_recursive() — Replaces elements from passed arrays into the first array recursively.
Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.3.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
array_replace_recursive() replaces the values of array with the same values from all the following arrays. 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 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 several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.
Signature
array_replace_recursive(array $array, array ...$replacements): array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $array | array | The array in which elements are replaced. |
| ...$replacements | array | Arrays from which elements will be extracted. |
Return value
Returns an array.
Example
A runnable snippet:
$base = array('citrus' => array("orange"), 'berries' => array("blackberry", "raspberry")); $replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry')); $basket = array_replace_recursive($base, $replacements); print_r($basket); $basket = array_replace($base, $replacements); print_r($basket);
Output:
Array ( [citrus] => Array ( [0] => pineapple ) [berries] => Array ( [0] => blueberry [1] => raspberry ) ) Array ( [citrus] => Array ( [0] => pineapple ) [berries] => Array ( [0] => blueberry ) )
See also
array_replace(), array_merge_recursive()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page array_replace_recursive() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.