DEV Community

Cover image for How to merge an array in PHP?
Programming Dive
Programming Dive

Posted on

How to merge an array in PHP?

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.

<?php
$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.

<?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.

<?php
$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.

<?php
$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.

<?php
$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.

<?php
$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.

<?php
$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.

<?php
$table_headings = ['sr_no', 'name', 'address'];
$row1 = ['1', 'Jason', 'Houston'];
print_r(array_combine($table_headings, $row1));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)