PHP array_replace_recursive() function

PHP array_replace() function
PHP array_reverse() function

The array_replace function replaces the values from the first array with the values of the following arrays recursively. You will get a clear understanding after going through the syntax and examples below.

You can assign one or multiple arrays to the array_replace function.

There are the following scenarios to be focused on for the array_replace function.

  1. If a key exist in array 1 found in the array 2, it will be replaced by the value of array 2.
  2. If the array 1 key does not exist in any of the following arrays, it will remain same in the result.
  3. If array 1 does not contains any key that the following arrays do, it will be created in the array 1.
  4. If multiple arrays are used, the latest array value will overwrite the value in the previous array.

What is the syntax of the array_replace_recursive function in PHP?

array_replace_recursive(array1, array2, array3, ...)
ParameterDescription
array1Array to replace the values of – Required
array2Array to replace the values with – Optional
array3,…More arrays to replace the values. Values from the last most array overwrite the previous ones – Optional
array_replace_recursive function in PHP

Examples of array_replace_recursive function

<?php
$array_1=array("a"=>array("1"),"b"=>array("2","3"));
$array_2=array("a"=>array("4"),"b"=>array("5"));
$array_3=array("a"=>array("6"),"b"=>array("7"));
print_r(array_replace_recursive($array_1,$array_2,$array_3));
?>

In the above example, we use multiple arrays with the array_replace_recursive method.

What is the difference between array_replace and array_replace_recursive function?

Understand and execute the following example script to have a clear difference between the array_replace and array_replace_recursive function.

<?php
$array_1=array("a"=>array("1"),"b"=>array("2","3"),);
$array_2=array("a"=>array("4"),"b"=>array("5"));

$res=array_replace_recursive($array_1,$array_2);
print_r($res);

$result=array_replace($array_1,$array_2);
print_r($res);
?>

PHP array_replace() function
PHP array_reverse() function

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top