How to append one array to another array in PHP

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Append arrays in PHP

There are many ways to append an array in PHP, and this article explores some of these options.

Introduction

Arrays in PHP are mutable meaning that you can add, remove and modify them in any way you want. You can add an element, or arrays to the end of an array, which we term as appending to arrays. This article explores how to append one array to another array in PHP. There are many options to explore so let’s cut the crap and jump straight to them.

append array in PHP

#1 – Append array in PHP using array_merge

PHP array_merge function merges two or more arrays. This function is simplistic with a straightforward merging policy. After merging, it reindexes numeric arrays. However, in the case of similar string keys, it assigns the latest occurring value. The following example clarifies these caveats and demonstrates how to append to array PHP.

<?php

$array1 = [1,2,3,4,5];
$array2 = [6,7,8,9,10];

 
$merged_array = array_merge($array1, $array2, $array3, $array4);
 
print_r($merged_array);
 
/*
OUTPUT
Array      
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    ]
*/
?>

The example appends array2 to array1 using array_merge in PHP. The arrays are reindexed in the output. The following example looks into string keys.

<?php

$array1 = ["Emp#1"=>"Franklin","Emp#2"=>"Richard","Emp#3"=>"Jake"];
$array2 = ["Emp#4"=>"Tyson","Emp#2"=>"Narnie","Emp#5"=>"Kylie"];
 
$merged_array = array_merge($array1, $array2);
 
print_r($merged_array);
 
/*
OUTPUT
Array
(
    [Emp#1] => Franklin
    [Emp#2] => Narnie  
    [Emp#3] => Jake    
    [Emp#4] => Tyson  
    [Emp#5] => Kylie  
)
*/
?>

The example above appends array1 to array2. Notice that the function assigns a later occurring value “Narnie” to the similar key in “Emp#2” in the arrays. However, sometimes this behavior is not desirable. So, PHP array_merge_recursive is a way out for this concern and that we see next.

#2 – Append array in PHP using array_merge_recursive

As the name suggests, PHP array_merge_recursive function merges two or more arrays recursively. The recursive nature opens an alternative to the behavior as seen with array_merge. The following example uses the same arrays from the previous example to append to array PHP.

<?php
$array1 = ["Emp#1"=>"Franklin","Emp#2"=>"Richard","Emp#3"=>"Jake"];
$array2 = ["Emp#4"=>"Tyson","Emp#2"=>"Narnie","Emp#5"=>"Kylie"];
 
$merged_array = array_merge_recursive($array1, $array2);
 
print_r($merged_array);
?>
/*
OUTPUT
Array
(
    [Emp#1] => Franklin
    [Emp#2] => Array
        (
            [0] => Richard
            [1] => Narnie
        )
 
    [Emp#3] => Jake
    [Emp#4] => Tyson
    [Emp#5] => Kylie
)
*/

The example appends the two arrays just as the array_merge. The difference is that the “Emp#2” key has both values instead of the latter overwriting the former.

#3 Append array PHP with the spread operator

Note: Spread operators are available from PHP 7.4, so if you are working in a version less than 7.4, this method may not work for you.

The spread operator unpacks an array like the example shows.

//OUTPUT: ['Kylie', 'Roberts']
$names = ['Kylie', 'Roberts'];
//OUTPUT: ['Amanda', Kylie', 'Roberts']
$more_names = ['Amanda', ...$names];

Similarly, the spread operator appends an array to an array in PHP.

<?php
$fruits = ['Apple','Orange','Mango'];
$more_fruits = ['Strawberry', 'Watermelon','Pear'];
 
$fruits = [...$fruits, ...$more_fruits];
 
//Output the array to console.
print_r($fruits);
 
/*
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Mango
    [3] => Strawberry
    [4] => Watermelon
    [5] => Pear
)
*/
?>

The same example with PHP array_push looks.

<?php
$fruits = ['Apple','Orange','Mango'];
$more_fruits = ['Strawberry', 'Watermelon','Pear'];
 
array_push($fruits, ...$more_fruits);
 
//Output the array to console.
print_r($fruits);
 
/*
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Mango
    [3] => Strawberry
    [4] => Watermelon
    [5] => Pear
)
*/
?>

#4 Append array PHP with a foreach loop.

There’s a more explicit way to add to a PHP array using a foreach loop with array_push function as follows.

<?php
$fruits = ['Apple','Orange','Mango'];
$more_fruits = ['Strawberry', 'Watermelon','Pear'];
 
foreach($more_fruits as $fruit)
{
    array_push($fruits, $fruit);
}
 
 
//Output the array to console.
print_r($fruits);
 
/*
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Mango
    [3] => Strawberry
    [4] => Watermelon
    [5] => Pear
)
*/
?>

The loop iterates through the array and appends elements sequentially to the array. 

Personal Opinion

These are all the options we have and out of these I personally prefer the spread operator for a linear merge. The reason is that it is a straightforward one-liner and good for clean coding. However, for a non-linear merge, I will prefer the array_merge_recursive function option. The recursive algorithm behind the scenes helps in retaining all values of identical keys.

Conclusion

This article explores many different options of how to append one array to another array in PHP. The first option uses array_merge followed by array_merge_recursive variant. The third option uses the spread operator available from PHP 7.4 and onwards. Finally, the last option uses a foreach loop with the array_push function. 

I hope you’ve liked this article. Stay tuned to learn more about PHP through intuitive tutorials, articles at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.