How to merge an array in PHP?

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.

So, the problem statement is when we work on the different functionalities which contain data stored in an array and wanted to combine them to be available in the single variable then what will be the options? So the solution is to merge them into a single array.

PHP has provided different functions to group different arrays into a 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);
// 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 the associative array in PHP.

<?php

$array1 = ['fruit'=>'', 'color'=>'orange'];
$array2 = ['color'=>'red'];

print_r(array_merge($array1, $array2));
// 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));
// 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 ));
// 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));
// 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));
// 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));
// OUTPUT

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

We can also provide + sign to merge two arrays. The syntax for it is quite simple.

<?php

$permanent_location = [
    'employee_home' => [
        'address' => 'LA'
    ]
];

$employment_location = [
    'employee_current' => [
        'address' => 'AL'
    ]
];

print_r($permanent_location+$employment_location);
// OUTPUT

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

array_merge vs +

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

php.net Documentation

There is quite different behavior between array_merge() and + operator. Let’s jump right into the example and see it in action.

<?php
$fruits = array("a" => "apple", "b" => "banana");
$fruits2 = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

print_r(array_merge($fruits, $fruits2));
print_r($fruits + $fruits2);
// OUTPUT

Array ( 
   [a] => pear 
   [b] => strawberry 
   [c] => cherry 
)

Array ( 
   [a] => apple 
   [b] => banana 
   [c] => cherry 
)

Now, we can see that using array_merge and + operator perform different operations on provided array.

Otherwise, there is 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));
// 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]
    ]
];
// 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));

Reindex array in PHP using array_combine()

array_combine can also be used to reindex an array. Well, we know that we can combine two arrays in which the first array will act as keys and another will be values. So if we want to rearrange our array and give the starting index as 1 then we can make code changes like this.

<?php

$arr =
[
    0 => [
        'name' => 'kevin',
        'address' => 'US'
    ],
    1 => [
        'name' => 'Jason',
        'address' => 'US'
    ]
];

$reindex = array_combine(range(1, count($arr)), array_values($arr));
// OUTPUT

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

So, we used inside array_combine() the first parameter as a blank array with keys starting from index 1 and count($arr) will give the total number of array elements.

The second parameter will be obviously the values only. Now, our final array will contain newly indexed elements.

Conclusion:

Using these three different inbuilt functions totally depends on the requirement. These three functions are beautifully crafted to be useful in different situations in various parts of the project.