PHP Tutorials
Aug 22, 2021

PHP Array_Merge() Function - Merge One or More Arrays Into One Array

Let's take a look at how we can use the php array_merge() function to merge arrays into one array.

Matt Payne
Matt Payne

We’re going to take a look at how we can use the php array_merge() function to merge one, two, or multiple arrays into one array. We’ll walk through various implementations and examples that show the extension of this php function. 

PHP Array_Merge() Function Introduction & Syntax


The PHP Array_Merge() function is a built-in php function that is used to merge the elements of one, two, or multiple arrays together into a single array. The elements of the arrays are appended to the end of the previous array in the input list. The function returns the resulting array, which will be empty if no arrays are added as arguments.

 array_merge ( array ...$arrays ) : array 


Parameters For Array_Merge() Function:

The only parameters are the given arrays you want to merge together, in the order you want them to concatenate to each other. These arrays are separated by commas.


$array1 = array("name" => "Matt", 24,80000);
$array2 = array("xyz", "xyz", "name" => "Matt", "Job" => "engineer");
$return_array = array_merge($array1, $array2);
print_r($return_array);


$Arrays

This is a variable list of arrays to merge together into a single array. If the elements in the arrays have string keys and two lists have the same string keys the later value for that key will overwrite the previous ones. In the case the arrays contain numeric keys the later element value will not overwrite the other values and will just be appended. The values with numeric keys will be renumbered with new incrementing keys starting at 0 in the resulting array. 


$array1 = array();
$array2 = array(1 => "data");
$return_array = array_merge($array1, $array2);


The result from this array merge is an array with one element:( [0] => data ).

Return Value For Array_Merge() Function:

The function returns a new array made up of concatenated elements from the input arrays. If no arrays are added as inputs the function will return an empty array. 



Quick Things To Know About Array_Merge() Function:

PHP version 7.4.0 added the ability to call this function without any parameters. 


Array_merge() was added in PHP 4.


While the array_merge() function appends array elements in order, the array_merge_recursive() function merges the arrays recursively. 


If only one array is passed the function will just return the same array.

PHP Array_Merge() Function Examples:

Let’s look at a wide variety of ways we can use the array_merge() function to merge multiple arrays into one. 


Simple Array_Merge() Function Examples:

This code example merges our two arrays together using two simple arrays.


$names1 = ['Matt'];

$names2 = ['Levi', 'Luka', 'Noah];

$return_array = array_merge($server_side, $client_side);

print_r($return_array);


The result array looks like this:


Array
(
    [0] => PHP
    [1] => JavaScript
    [2] => CSS
    [3] => HTML
)


Notice how the result array adds numeric keys when the passed arrays do not have keys.


Using The Array_Merge() Function With String Keys

This example shows how the array_merge() function removes the duplicate values when the string key is an exact match between the two arrays. The function uses the later value between the two array elements.



$hours_exe = [
	'Matt' =>40,
	'Noah' =>2,
	'Heather' =>10
];

$hours_dev = [
	'Matt' => 50,
	'Noah' => 5,
	'Levi' =>31,
];

$work_hours = array_merge($hours_exe, $hours_dev);

print_r($work_hours);


The output from the above example:


Array
(
    [Matt] => 50
    [Noah] => 5
    [Heather] => 10
    [Levi] => 31
)

You’ll notice that for the two elements that have the same key the array_merge() function uses the later value in the arrays, but still puts them in order given that both those string keys appear before anything else in the first array. Once those values are changed the rest of the elements are concatenated in order.

Merge 2 Arrays With Numeric Keys With Array_Merge()

Here’s an example of what happens when we merge 2 arrays with numeric keys together.


$a1 = array(1=>'Matt', 2=>40);
$a2 = array(1=>'Noah', 2=>5);
print_r(array_merge($a1, $a2));



The resulting array is:


Array
(
    [0] => Matt
    [1] => 40
    [2] => Noah
    [3] => 5
)


You’ll notice numeric keys that are the same do not get combined and values replaced like with string keys. The function more or less ignores the numeric keys and just concatenates the two arrays values in order with new keys starting from zero.

Tips From A Real Data Processing Use Case

One of the workflow processes used in systems like this product recognition software build is managing multiple extending pipelines all related to the same input, usually based on a unique_id(). Input data such as an image would come in and be passed to different pipelines to perform various operations. In a parallel architecture you can end up with duplicates if the same image is accidentally passed in multiple times especially in the case of extracting from a video feed. 


If the identifier in the array of results from the different extending pipelines is a unique_id numeric value we’ll just reindex the values and pass the duplicates along as we’ve seen. Given these are exact duplicates we’d rather the array_merge() function acted as it does with string keys. Let’s take a look at what you can do.


If you want to append the second array to the first while not reindexing and not overwriting the elements in our first array we can use the array union operator instead of array_merge().


$array1 = array(9053997 => 'SKU:645', 121 => 'yes', 6297601 => 'True');
$array2 = array(9053997 => 'SKU:645', 121 => 'no', 997 => 'True');
$result = $array1 + $array2;
var_dump($result);

The numeric keys in the first array will be preserved, and if a key exists in both of the input arrays then the element value in the first array will be passed. The results from the array union look like this:


array {
  [9053997]=>
  string(7) "SKU:645"
  [121]=>
  string(3) "yes"
  [6297601]=>
  string(4) "true"
  [997]=>
  string(4) "True"

}


The way array_merge() works with numeric keys is not a bug! This functionality is laid out in the PHP documentation.

More Examples Of Using The Array_Merge() Function

Let’s look at some unique and exciting ways we can merge arrays.


Php Combine Arrays With Non Array Types

We can cast values to an array in the parameters of array_merge() to merge arrays.



$first = 'Matt';
$val = array(1 => 'Payne');
$return_array = array_merge((array)$first, (array)$val);
print_r($return_array);



The output is a resulting array with the first value being indexed at [0].

What is The Difference Between Array_Merge() and Array_Merge_Recursive() in PHP?

The key difference between these two array merging functions is what they do when the arrays have the same keys. Instead of overriding and replacing the keys as array_merge() does, the array_merge_recursive() function makes an array for the element.


array_merge() example

In this example above the element in question is “b”. As we’ve seen before the array_merge() function would remove the duplicate key element in some form based on if it was a string key or numeric key. In the case of array_merge_recursive we’re going to have an element that is an array with “green” and “yellow” as values in the array. 


Array ( [a] => red [b] => Array ( [0] => green [1] => yellow ) [c] => blue )


Quick note: Two or more arrays can be merged via the spread operator as well. 


Common Error: Array_merge(): Argument #2 Is Not An Array

Let’s look at different situations that lead to this very common error.


One of the Input Arrays is not an Array

As you can imagine this is the most simple explanation for this error. One or more arrays you’re passing in is not an array, and either needs to be adjusted or cast to an array. 


Summary

Array_Merge() works to merge arrays together and append array elements to each other. Arrays with matching keys create different logic when matching key’s elements together based on if we have the same string keys or numbered keys.


Instant Access To PHP Case Studies

Read real use cases and whitepapers using PHP