How to combine two multidimensional array in php?

how to join two multidimensional arrays in php? I have two multidimensional arrays A and B. I need to join A and B to form a new array C as follows

$A = array( 
array("a1"=>1,"b1"=>2,"c1"=>"A"), 
array("a1"=>1,"b1"=>16,"c1"=>"Z"), 
array("a1"=>3,"b1"=>8,"c1"=>"A")); 

$B = array( 
array("a2"=>1,"b2"=>2,"b2"=>"A"), 
array("a2"=>1,"b2"=>16,"b2"=>"G"), 
array("a2"=>3,"b2"=>8,"b2"=>"A")); 

//join A and B to form C

$C=array( 
array("a1"=>1,"b1"=>2,"c1"=>"A"), 
array("a1"=>1,"b1"=>16,"c1"=>"Z"), 
array("a1"=>3,"b1"=>8,"c1"=>"A"),
array("a2"=>1,"b2"=>2,"b2"=>"A"), 
array("a2"=>1,"b2"=>16,"b2"=>"G"), 
array("a2"=>3,"b2"=>8,"b2"=>"A"));

Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Start your free 14-day trial today.

If you want to join two multidimensional arrays in PHP, you should still use array_merge, and not array_merge_recursive. Confused? So was I. Let's explain what's happening.

Let's first explain what array_merge_recursive does, take for example these two arrays:

$first = [
    'key' => 'original'
];

$second = [
    'key' => 'override'
];

Using array_merge_recursive will result in the following:

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

Instead over overriding the original key value, array_merge_recursive created an array, with the original and new value both in it.

While that looks strange in this simple example, it's actually more useful in cases where one of the values already is an array, and you want to merge another item in that array, instead of overriding it.

$first = [
    'key' => ['original']
];

$second = [
    'key' => 'override'
];

In this case, array_merge_recursive will yield the same result as the first example: it takes the value from the $second array, and appends it to the value in the $first array, which already was an array itself.

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

So if you want to merge multidimensional arrays, you can simply use array_merge, it can handle multiple levels of arrays just fine:

$first = [
    'level 1' => [
        'level 2' => 'original'
    ]
];

$second = [
    'level 1' => [
        'level 2' => 'override'
    ]
];

array_merge($first, $second);

// [  
//     'level 1' => [
//         'level 2' => 'override'
//     ]
// ]

All of that being said, you could also use the + operator to merge multidimensional arrays, but it will work slightly different compared to array_merge.

Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what's happening on this blog, you can follow me on Twitter or subscribe to my newsletter:

Please check the detailed post about How to merge an array in PHP

To merge arrays, PHP has provided inbuilt functions that will take arrays and will provide final output as a merged array. In this tutorial, we’ll see how to merge an array in PHP.

PHP has provided different functions to group different arrays into single.

  • array_merge()
  • array_combine()
  • array_merge_recursive()

Merge two arrays using array_merge()

We can merge two or more arrays using array_merge() and its syntax is quite simple-

array_merge ([ array $... ] ) : array

Here, we can pass as many arrays (as arguments) as possible and the expected output will always be an array.

So, in array_merge() the resultant array will contain one array appended to another array which means the first array argument will be considered as a parent/reference array to which all the other array elements will be appended.


$fruits = ['apple','banana'];
$flowers = ['rose', 'lotus'];
$final_array = array_merge($fruits, $flowers);

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array ( 
   [0] => apple 
   [1] => banana 
   [2] => rose 
   [3] => lotus 
)

Now, consider a situation wherein the second array, the same string key is present. So, in such cases, the latter will override the first value.

In the below example, let’s see how to merge associative array in php.


$array1 = ['fruit'=>'', 'color'=>'orange'];
$array2 = ['color'=>'red'];
print_r(array_merge($array1, $array2));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array ( 
    [fruit] =>
    [color] => red 
)

However, if the arrays contain numeric keys, the later value will not overwrite the previous/original value, but it will be appended and a new index will be allocated to it.


$arr1 = [
            1,
            1=>"Jack",
            "name"=> "Kevin"
        ];
$arr2 = [
            3,
            1=>"Sparrow", 
            9,
            "name" => "Jason"
        ];
print_r(array_merge($arr1, $arr2));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array ( 
   [0] => 1 
   [1] => Jack
   [name] => Jason 
   [2] => 3 
   [3] => Sparrow 
   [4] => 9 
)

So, we can see that we have two same numeric and string keys in $arr1 & $arr2. But in the case of numeric keys, it gets appended and for strings keys, it gets overrides.

Now, if the provided array does not have numeric/string keys and only has values like ['NY', 'AL', 'AR'] then those will be indexed in increment order.


$arr = [
            1, 
            1=>"Jack", 
            "name"=> "Kevin"
        ];
$states = [
            'NY',
            'AL',
            'AR'
        ];
print_r(array_merge($arr, $states ));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array ( 
   [0] => 1 
   [1] => Jack 
   [name] => Kevin 
   [2] => NY 
   [3] => AL 
   [4] => AR 
)

Merge multidimensional array in php

Merging a multidimensional array is the same as that of a simple array. It takes two arrays as input and merges them.

In a multidimensional array, the index will be assigned in increment order and will be appended after the parent array.


$arr = [
            [
                'name' => 'kevin', 
                'address' => 'US'
            ]
];
$arr2 = [
            [
                'name' => 'Jason', 
                'address' => 'US'
            ]
];
print_r(array_merge($arr, $arr2));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array
(
   [0] => Array
       (
           [name] => kevin
           [address] => US
       )
   [1] => Array 
       ( 
           [name] => Jason 
           [address] => US 
       )
)

Now, let’s take the example of an employee who has two addresses. One is his/her permanent address and another is work address. Now, we fetched both the addresses and try to merge them in a single array.


$permanent_location = [
    'employee' => [
        'address' => 'LA'
    ]
];
$employment_location = [
    'employee' => [
        'address' => 'AL'
    ]
];
print_r(array_merge($permanent_location, $employment_location));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array ( 
     [employee] => Array 
            ( 
               [address] => AL
            ) 
)

Well, it looks weird right. We wanted to get both the address merged into a single array. But this is not going to happen because as we can see both the array keys are the same and are string keys. So the quickest solution will be to store both the address in different indexes.


$permanent_location = [
    'employee_home' => [
        'address' => 'LA'
    ]
];
$employment_location = [
    'employee_current' => [
        'address' => 'AL'
    ]
];
print_r(array_merge($permanent_location, $employment_location));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array
(
   [employee_home] => Array
       (
           [address] => LA
       )
   [employee_current] => Array 
       ( 
           [address] => AL 
       )
)

Otherwise user another useful PHP function to merge array recursively i.e, array_merge_recursive()

Merge two arrays using array_merge_recursive()

Now, we’ll use the same above example and see how array_merge_recursive() work efficiently to not override the parent key instead it uses the same key and add those different values inside it as an array.

print_r(array_merge_recursive($permanent_location, $employment_location));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array
(
    [employee] => Array
       (
           [address] => Array
              (
                  [0] => LA
                  [1] => AL
              )
       )
)

Now, suppose we have an array value for address ‘LA’ inside our first array $permanent_location as follows then that value will also get recursively merged to the same key (address)

$permanent_location = [
    'employee' => [
        'address' => ["name"=>"Albert", 2=>222]
    ]
];

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Array
(
    [employee] => Array
      (
         [address] => Array
            (
                [name] => Albert
                [2] => 222
                [3] => 999
            )
      )
)

Combine arrays using array_combine()

array_combine() is used to creates an array by using one array for keys and another for its values.

So, we can use this function in different situations like user profile page where the user’s id, name, and address can be stored in one array and users’ actual information can be stored in another array.


$table_headings = ['sr_no', 'name', 'address'];
$row1 = ['1', 'Jason', 'Houston'];
print_r(array_combine($table_headings, $row1));

Enter fullscreen mode Exit fullscreen mode

How will you merge two multidimensional arrays to get the required outcome?

Using NumPy, we can perform concatenation of multiple 2D arrays in various ways and methods..
Method 1: Using concatenate() function..
Method 2: Using stack() functions:.
Method 3: Using hstack() function..
Method 4: Using vstack() function..
Method 5: Using dstack() function..

How can I merge two arrays in PHP?

PHP array_merge() Function.
Merge two arrays into one array: $a1=array("red","green"); $a2=array("blue","yellow"); ... .
Merge two associative arrays into one array: $a1=array("a"=>"red","b"=>"green"); $a2=array("c"=>"blue","b"=>"yellow"); ... .
Using only one array parameter with integer keys: $a=array(3=>"red",4=>"green");.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

How do you merge two arrays by summing the merged values?

array_merge does merge two arrays while retaining all keys. But you want to sum the value of identical keys of two arrays, which is something else.