How to Append an Array to Another in PHP
Imagine that you have two arrays and want to append one to another.
Here, we will illustrate the main functions that are used to meet that goal.
Using the array_merge Function
Let’s see how array_merge is used for appending an array to another. Note that after merging the arrays, this function returns a new array.
The example is shown below:
<?php
$arr1 = ["W3", "w3d"];
$arr2 = ["W3docs", "Computer science portal"];
// Getting the merged array in the first array itself.
$arr1 = array_merge($arr1, $arr2);
echo "arr1 Contents:";
// Using the for each loop to print all the array elements.
foreach ($arr1 as $value) {
echo $value . "\n";
}
?>
arr1 Contents: W3 w3d W3docs Computer science portal
Using the array_push Function
Let’s consider an alternative method to append an array to another with PHP.
Here, we will use the array_push function. Unless, array_merge, it pushes the second array element into the first one in-place.
For a better perception, look at the example, below:
<?php
$arr1 = [1, 2];
$arr2 = [3, 4];
// arr2 elements are being pushed in the arr1.
array_push($arr1, ...$arr2);
echo "arr1 = ";
// Using the for each loop to print all the array elements.
foreach ($arr1 as $value) {
echo $value . ' ';
}
?>
arr1 = 1 2 3 4
Array unpack operator
<?php
$array1 = [1, 2];
$array2 = [3, 4];
$array = [...$array1, ...$array2];
var_dump($array);
?>
The array_merge and array_push Functions in PHP
The array_merge function is aimed at merging one or more arrays. It merges them together in a way that values of one get appended to the end of the previous one. As a result, it returns a new array.
In case the same string keys exist for the input arrays, the later one overwrites the previous.
The array_push function is aimed at pushing one or more elements toward the end of the array. It considers an array as a stack, pushing the passed variables towards the end of the array.