Skip to content

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 use array_merge to append an array to another

php
<?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

console
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. Unlike array_merge, 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
<?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

console
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
<?php

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

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

var_dump($array);

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

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.

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 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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.