How to merge an array in PHP?
Tags: php, array, merge
Published: 2020-11-01 14:52:25

Please check the detailed post about <a href="https://programmingdive.com/how-to-merge-an-array-in-php/">How to merge an array in PHP</a>

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.
<ul>
<li>array_merge()</li>
<li>array_combine()</li>
<li>array_merge_recursive()</li>
</ul>

<h3>Merge two arrays using array_merge()</h3>

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

<blockquote>array_merge ([ array $... ] ) : array</blockquote>

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

So, in <code>array_merge()</code> 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
<?php
$fruits = ['apple','banana'];
$flowers = ['rose', 'lotus'];
$final_array = array_merge($fruits, $flowers);
```
<pre>
// OUTPUT

Array ( 
   [0] => apple 
   [1] => banana 
   [2] => rose 
   [3] => lotus 
)
</pre>
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
<?php
$array1 = ['fruit'=>'', 'color'=>'orange'];
$array2 = ['color'=>'red'];
print_r(array_merge($array1, $array2));
```
<pre>
// OUTPUT

Array ( 
    [fruit] =>
    [color] => red 
)
</pre>
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
<?php
$arr1 = [
            1,
            1=>"Jack",
            "name"=> "Kevin"
        ];
$arr2 = [
            3,
            1=>"Sparrow", 
            9,
            "name" => "Jason"
        ];
print_r(array_merge($arr1, $arr2));
```
<pre>
// OUTPUT

Array ( 
   [0] => 1 
   [1] => Jack
   [name] => Jason 
   [2] => 3 
   [3] => Sparrow 
   [4] => 9 
)
</pre>
So, we can see that we have two same numeric and string keys in <code>$arr1</code> & <code>$arr2</code>. 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 <code>['NY', 'AL', 'AR']</code> then those will be indexed in increment order.
```php
<?php
$arr = [
            1, 
            1=>"Jack", 
            "name"=> "Kevin"
        ];
$states = [
            'NY',
            'AL',
            'AR'
        ];
print_r(array_merge($arr, $states ));
```
<pre>
// OUTPUT

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

<h3>Merge multidimensional array in php</h3>
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
<?php
$arr = [
            [
                'name' => 'kevin', 
                'address' => 'US'
            ]
];
$arr2 = [
            [
                'name' => 'Jason', 
                'address' => 'US'
            ]
];
print_r(array_merge($arr, $arr2));
```
<pre>
// OUTPUT

Array
(
   [0] => Array
       (
           [name] => kevin
           [address] => US
       )
   [1] => Array 
       ( 
           [name] => Jason 
           [address] => US 
       )
)
</pre>
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
<?php
$permanent_location = [
    'employee' => [
        'address' => 'LA'
    ]
];
$employment_location = [
    'employee' => [
        'address' => 'AL'
    ]
];
print_r(array_merge($permanent_location, $employment_location));
```
<pre>
// OUTPUT

Array ( 
     [employee] => Array 
            ( 
               [address] => AL
            ) 
)
</pre>
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
<?php
$permanent_location = [
    'employee_home' => [
        'address' => 'LA'
    ]
];
$employment_location = [
    'employee_current' => [
        'address' => 'AL'
    ]
];
print_r(array_merge($permanent_location, $employment_location));
```
<pre>
// OUTPUT

Array
(
   [employee_home] => Array
       (
           [address] => LA
       )
   [employee_current] => Array 
       ( 
           [address] => AL 
       )
)
</pre>
Otherwise user another useful PHP function to merge array recursively i.e, <code>array_merge_recursive()</code>

<h3>Merge two arrays using array_merge_recursive()</h3>
Now, we’ll use the same above example and see how <code>array_merge_recursive()</code> work efficiently to not override the parent key instead it uses the same key and add those different values inside it as an array.
```php
print_r(array_merge_recursive($permanent_location, $employment_location));
```
<pre>
// OUTPUT

Array
(
    [employee] => Array
       (
           [address] => Array
              (
                  [0] => LA
                  [1] => AL
              )
       )
)
</pre>
Now, suppose we have an array value for address ‘LA’ inside our first array <code>$permanent_location</code> as follows then that value will also get recursively merged to the same key (address)
```php
$permanent_location = [
    'employee' => [
        'address' => ["name"=>"Albert", 2=>222]
    ]
];
```
<pre>
// OUTPUT

Array
(
    [employee] => Array
      (
         [address] => Array
            (
                [name] => Albert
                [2] => 222
                [3] => 999
            )
      )
)
</pre>
<h3>Combine arrays using array_combine()</h3>
<code>array_combine()</code> 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
<?php
$table_headings = ['sr_no', 'name', 'address'];
$row1 = ['1', 'Jason', 'Houston'];
print_r(array_combine($table_headings, $row1));
```