W3docs

How to Append an Array to Another in PHP

While working with PHP, developers wonder how to append one array to another. This snippet is dedicated to the exploration of functions that help to do it.

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 <kbd class="highlighted">array_merge</kbd> 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 use array_merge to append an array to another

<?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";
}

?>

php array_merge to append an array to another, output

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 <kbd class="highlighted">array_push</kbd> function. Unlike <kbd class="highlighted">array_merge</kbd>, it pushes the elements of the second array into the first one in-place.

For a better understanding, look at the example below:

php use array_push to append an array to another

<?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 . ' ';
}

?>

php array_push to append an array to another, output

arr1 = 1 2 3 4
Note

You can also use the + operator to merge arrays. However, it is not recommended for simple appending because it merges arrays with left-side precedence and preserves numeric keys instead of reindexing them, which can lead to unexpected results.

Array unpack operator

Example of Array unpack operator in PHP

<?php

$array1 = [1, 2];
$array2 = [3, 4];

$array = [...$array1, ...$array2];

var_dump($array);

?>
array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

The array_merge and array_push Functions in PHP

The <kbd class="highlighted">array_merge</kbd> 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.

Note: array_merge reindexes numeric keys, whereas array_push preserves them.

In case the same string keys exist for the input arrays, the later one overwrites the previous.

The <kbd class="highlighted">array_push</kbd> 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.