Difference between PHP array_merge_recursive vs array_replace_recursive

Summary:

The difference is that array_merge_recursive doesn’t overwrite values of the same keys, rather append them

PHP array_merge_recursive vs array_replace_recursive 

This article features PHP array_merge_recusrive vs array_replace_recursive. The difference is that array_merge_recursive doesn’t overwrite values of the same keys, rather append them. However, the array_replace_recursive uses an algorithm that tends to recursively overwrite and replacement values of the arrays

Introduction

PHP array_merge_recursive and array_replace_recursive are sometimes sources of confusion. They are both recursive functions, ideal for deeply nested array structures. However, they are different in terms of functionality. Their names may imply their functions, but yet they are not straightforward. So, we recommend doing your research before jumping in. Nevertheless, the article also includes a quick overview of these functions.

FuelingPHP includes an in-depth article about PHP array_merge_recursive. These recursive functions have their non-recursive counterparts, but they are not essential for this article. You can always learn about them at FuelingPHP. This article overviews these functions and includes intuitive examples. These examples are enough for highlighting the differences, but the article includes a section that summarizes the PHP array_merge_recursive vs array_replace_recursive.

PHP array_merge_recursive : An Overview

Here’s an overview with a textual description of the function, and its example.

Function Signature

array_merge_recursive(array ...$arrays): array

Description

PHP array_merge_recursive accepts a variable number of arrays and merges them. The merging is recursive, and the algorithm works by appending values of the same string keys in an array. However, similar numeric arrays are appended directly by increasing numeric order.

Example#1 

Here’s a basic example of this function.

<?php
$arr1 = ["Countries"=>"US", "Cities" => ["Newyork", "Paris"], "Pacific"];
$arr2 = ["Countries"=>"Germany", "Cities"=> ["Cairo"], "Atlantic"];
 
print_r(array_merge_recursive($arr1, $arr2));
 
/*
OUTPUT
Array
(
    [Countries] => Array
        (
            [0] => US
            [1] => Germany
        )
 
    [Cities] => Array
        (
            [0] => Newyork
            [1] => Paris
            [2] => Cairo
        )
 
    [0] => Pacific
    [1] => Atlantic
)
*/
?>

The function recursively merges values of the same string keys and returns a well-organized array. Also, observe that the numeric keys are just stacked in ascending order.

Example#2

Here’s another example of array_merge_recursive that uses a relatively complex array.

<?php
$array1 = [
    "User#1" => ["Status"=>"Active","Roles"=>["Monitor","Collaborator"],"Hi! I am junior developer"],
    "User#2" => ["Status"=>"Offline","Roles"=>["Developer","QA"],"Hi! I am QA engineer"],
    "User#3" => ["Status"=>"Left","Roles"=>["Trainee","UI/UX"],"Hi! I am UI/UX deisgner"],
];
$array2 = [
    "User#1" => ["Roles"=>"Developer","I develop the backend system"],
    "User#2" => ["I design the UI/UX of the application"],
];
$array3 = [
    "User#3" => ["Roles"=>["Trainee","UI/UX"],"MovedTo"=>"Project Zero"],
    "User#4" => ["Status"=>"Active","Roles"=>["Project Manager"]],
];
 
$merged_array = array_merge_recursive($array1, $array2, $array3);
 
print_r($merged_array);
 
 
?>

Here’s the output.

/*
OUTPUT
Array
(
    [User#1] => Array
        (
            [Status] => Active
            [Roles] => Array
                (
                    [0] => Monitor
                    [1] => Collaborator
                    [2] => Developer
                )
 
            [0] => Hi! I am junior developer
            [1] => I develop the backend system
        )
 
    [User#2] => Array
        (
            [Status] => Offline
            [Roles] => Array
                (
                    [0] => Developer
                    [1] => QA
                )
 
            [0] => Hi! I am QA engineer
            [1] => I design the UI/UX of the application
        )
 
    [User#3] => Array
        (
            [Status] => Left
            [Roles] => Array
                (
                    [0] => Trainee
                    [1] => UI/UX
                    [2] => Trainee
                    [3] => UI/UX
                )
 
            [0] => Hi! I am UI/UX deisgner
            [MovedTo] => Project Zero
        )
 
    [User#4] => Array
        (
            [Status] => Active
            [Roles] => Array
                (
                    [0] => Project Manager
                )
 
        )
 
)
*/

Voila! The function groups the information of the same users based on the key values. A good thing about this function is that it doesnot overwrite data, thus no chanes of data loss.

PHP array_replace_recursive : An Overview

Here’s an overview with textual description of the function, and its example.

Function Signature

array_replace_recursive(array $array, array …$replacements): array

Description

PHP array_replace_recursive accepts an array along with a list of replacement arrays. The replacement arrays work by replacing the value of the first array based on the key values. The function replaces the value of the first array with the latest replacement array. For instance, if there are three replacement arrays, the latest one is the third replacement array.

If the value to be replaced is scalar, the function replaces it as a whole. If the value is an array, the function recursively replaces its values. However, if a key exists in the second array but not in the first one, this function creates the key in the first array.

The example will clarify this further and simulate what the text describes.

Example#1

For better insights, the example features the same array as seen in example#1 from the preceding section.

<?php
$arr1 = ["Countries"=>"US", "Cities" => ["Newyork", "Paris"], "Pacific"];
$arr2 = ["Countries"=>"Germany", "Cities"=> ["Cairo"], "Atlantic"];
 
print_r(array_replace_recursive($arr1, $arr2));
 
/*
OUTPUT
Array
(
    [Countries] => Germany
    [Cities] => Array
        (
            [0] => Cairo
            [1] => Paris
        )
 
    [0] => Atlantic
)
*/
?>

Let see what’s happening.

  • The first array has “US” value for the key “Countries”. Just because it is a scalar value, the function replaces this value with the value “Germany” from the second array.
  • The “Cities” key has an array, [“Newyork, “Paris”]. The second array replaces the value “Newyork” only. That’s because the function recursively apply the same algorithm to this array.
  •  The third element “Pacific” is replaced by “Atlantic”  by the same logic the function replaces “US”.

Example#2

Here’s another example reusing the array with some changes.

<?php
$arr1 = ["Countries"=>"US", "Cities" => ["Newyork", "Paris"], "Pacific"];
$arr2 = ["Countries"=>"Germany", "Cities"=> ["Cairo"], "Atlantic"];
$arr3 = ["Countries"=>"France","Cities"=>["Baghdad", "Islamabad", "New Delhi"], "Continent"=> "Africa"];
 
print_r(array_replace_recursive($arr1, $arr2, $arr3));
 
/*
OUTPUT
Array
(
    [Countries] => France
    [Cities] => Array
        (
            [0] => Baghdad
            [1] => Islamabad
            [2] => New Delhi
        )
 
    [0] => Atlantic
    [Continent] => Africa
)
*/
?>

As there’s a third array now. So, the “Countries” key has the value “France” just because it appears latest. The “Cities” array has been replaced recursively. Also, the resulting array has an extra key from “Continent” with the value “Africa”, and it comes from the third array.

PHP array_merge_recursive vs array_replace_recursive 

So, the overview and examples of both functions clarify the differences between them. The difference is that array_merge_recursive doesn’t overwrite values of the same keys, rather append them. However, the array_replace_recursive uses an algorithm that tends to recursively overwrite and replace values of the arrays. So, the resulting array from both these functions differs drastically.

Use Case – PHP array_merge_recursive vs array_replace_recursive 

A practical example would be working with configuration files. A configuration file includes metadata about your project. For instance, here are two arrays having configuration settings.

$old_config = [
    "src" => '/project-src',
    "dest" => '/project-dest',
    "script" => 'run --start',
    "version" => '1.0',
    "author" => 'Alex'
];
 
$new_config = [
    "src" => '/project-src',
    "dest" => '/project-dest-new',
    "script" => 'run',
    "version" => '1.1',
    "author" => 'Alex'
];

Some settings have been updated and the old configuration needs updates. What do you think is the right pick for this case: array_merge_recursive or array_replace_recursive. Obviously, array_replace_recrusive. The array_merge_recursive would keep both the versions, and that will surely mess up the entire settings.

Here’s the output with array_replace_recursive.

Array
(
    [src] => /project-src
    [dest] => /project-dest-new
    [script] => run
    [version] => 1.1
    [author] => Alex
)

All the necessary updates have been applied.

Conclusion 

The article overviews PHP array_merge_recursive and array_replace_recusrive and includes examples of both. The examples use a similar array to emphasize the difference. Finally, the article includes a textual description of PHP array_merge_recursive vs array_replace_recursive. Hopefully, this article clarifies and helps in learning about these functions. Stay tuned for more informative PHP content at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems