PHP array_merge_recursive function

Last Updated: February 13, 2022

array_merge_recursive – merge one or more arrays together. Values are appended to the end of the one array.

What is difference between array_merge_recursive function and the array_merge() function?

When you have two or more array elements that have the same key normally, it will override the value but with array_merge_recursive() function makes the value as an array. You can see the example

Syntax

 array_merge_recursive(array ...$arrays): array

Supports (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

Parameters

Parameter Description
arrays Required. list of arrays for merging

Return Value

Returns an array

Example

Merging two arrays

<?php

$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);

?>

Output

Array ( 
[color] => Array ( 
                    [favorite] => Array ( [0] => red [1] => green ) 
                    [0] => blue 
                 ) 
[0] => 5 
[1] => 10 
) 
Test