1

Hi I am having a difficult to understand the difference between these two function in php array_replace and array_replace_recursive.

array array_replace_recursive ( array $array1 , array $array2 [, array $... ] )

and

array array_replace ( array $array1 , array $array2 [, array $... ] )

and thanks in advance

2
  • 3
    Do you know what the word recursive means? Its basically that if you have multi-dimensional arrays, it the function will be performed on the sub-arrays too instead of just the parent array. Commented Mar 23, 2017 at 2:31
  • Look at Example #1 at php.net/manual/en/function.array-replace-recursive.php, as it shows the difference in results from the 2 functions Commented Mar 23, 2017 at 2:33

1 Answer 1

4

The difference arises when you have arrays within arrays. Taking from here, let's create two arrays:

$base = array('citrus' => array( "orange") , 
              'berries' => array("blackberry", "raspberry"), 
             );
$replacements = array('citrus' => array('pineapple'), 
                      'berries' => array('blueberry')
                );

If we do

$basket = array_replace($base, $replacements);

We will get

Array
(
[citrus] => Array
    (
        [0] => pineapple
    )

[berries] => Array
    (
        [0] => blueberry
    )

)

where the array "blueberry" has replaced the array "blackberry","raspberry". If instead we do

$basket = array_replace_recursive($base, $replacements);

we will get

Array
(
[citrus] => Array
    (
        [0] => pineapple
    )

[berries] => Array
    (
        [0] => blueberry
        [1] => raspberry
    )

)

Now the first element in the array "blueberry" has replaced the first element in the array "blackberry","raspberry". So it's an array replacement within an array replacement, or a recursive replacement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.