array_merge_recursive() function in PHP


The array_merge_recursive() function merges one or more arrays into one array recursively. The difference between this function and array_merge() is that if two or more elements have the same key, the array_merge_recursive() function forms the value as an array. In this case, array_merge() function considers the last one.

Syntax

array_merge_recursive(arr1, arr2, arr3, …)

Parameters

  • arr1 − Initial array to merge

  • arr2 − Another array

  • arr3 − Another array

Return

The array_merge_recursive() function returns an array in which the elements of all arrays passed in parameters are merged.

The following is an example that merges two array with a key repeated in the second array. In this case the array_merge_recursive() function forms the value as an array.

Example

Live Demo

<?php
   $arr1 = array("p"=>"one","q"=>"two");
   $arr2 = array("q"=>"three","r"=>"four");
   print_r(array_merge_recursive($arr1,$arr2));
?>

Output

Array
(
   [p] => one
   [q] => Array
      (
         [0] => two
         [1] => three
      )
      [r] => four
)

Updated on: 30-Jul-2019

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements