Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_replace_recursive()

Example

Recursively replace the values in the first array with the values from the second array.

<?php
$a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”),);
$a2=array(“a”=>array(“yellow”),“b”=>array(“black”));
print_r(array_replace_recursive($a1,$a2));
?>

Definition and Usage

The array_replace_recursive() function recursively replaces the values in the first array with values from subsequent arrays.

Tip: You can pass one or more arrays to the function.

If a key from the first array exists in the second array, its value in the first array will be replaced by the value from the second array. If a key exists only in the first array, it remains unchanged. If a key exists in the second array but not in the first array, it will be added to the first array. When multiple arrays are provided, values from later arrays will overwrite those from earlier arrays.

 

Note: If you do not specify keys for the arrays, this function will behave the same as array_replace().

Syntax

array_replace_recursive(array1, array2, array3, …)

Parameter Values

Parameter

Description

array1

Required. Defines an array.

array2

Optional. Specifies an array that will replace the values in the first array.

array3,…

Optional. Specifies additional arrays to replace the values in array1 and array2, etc. Values from later arrays will overwrite those from earlier ones.

Technical Details

 

Return Value:

Returns the updated array with replaced values, or NULL if an error occurs.

PHP Version:

5.3.0+

More Examples

Example

Multiple arrays:

<?php
$a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”));
$a2=array(“a”=>array(“yellow”),“b”=>array(“black”));
$a3=array(“a”=>array(“orange”),“b”=>array(“burgundy”));
print_r(array_replace_recursive($a1,$a2,$a3));
?>

Example

Differences between array_replace() and array_replace_recursive():

<?php
$a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”),);
$a2=array(“a”=>array(“yellow”),“b”=>array(“black”));

$result=array_replace_recursive($a1,$a2);
print_r($result);

$result=array_replace($a1,$a2);
print_r($result);
?>