Home »
PHP
PHP Array array_merge_recursive() Function (With Examples)
In this tutorial, we will learn about the PHP array_merge_recursive() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP array_merge_recursive() function
The array_merge_recursive() function is used to merge two or more arrays, it returns a new array with merged elements. The only difference between array_merge() and array_merge_recursive() function is that it merges the values having the same key as an array instead of overriding the values.
Syntax
The syntax of the array_merge_recursive() function:
array_merge_recursive(array1, array2,...);
Parameters
The parameters of the array_merge_recursive() function:
- array1, array2, ...: It accepts two or more arrays and returns a new array with merged elements.
Return Value
The return type of this method is array, it returns an array of values resulted from merging the arguments together. If called without any arguments, returns an empty array. [Source]
Sample Input/Output
Input:
$arr1 = array("a" => "Hello", "b" => "Hi");
$arr2 = array("a" => "Okay!", "d" => "Nothing");
Output:
Array
(
[a] => Array
(
[0] => Hello
[1] => Okay!
)
[b] => Hi
[d] => Nothing
)
PHP array_merge_recursive() Function Example
<?php
$arr1 = array("a" => "Hello", "b" => "Hi");
$arr2 = array("a" => "Okay!", "d" => "Nothing");
//merging arrays
$arr3 = array_merge_recursive($arr1, $arr2);
//printing
print_r ($arr3);
?>
Output
The output of the above example is:
Array
(
[a] => Array
(
[0] => Hello
[1] => Okay!
)
[b] => Hi
[d] => Nothing
)
To understand the above example, you should have the basic knowledge of the following PHP topics: