array_push() and array_merge() – Append Into Array In PHP

PHP provides the array in order to store multiple items in a single variable. Array items can be provided during the array definition but can be also added later by using the array_push() method. In this tutorial, we will learn how to append new items into an array. The array_push() method can be used to add single or multiple items into an existing array. The array_push() method is provided with the PHP version 4.0 and later.

array_push() Syntax

The array_push() method has the following syntax where 2 parameters are provided and both of them are required.

array_push(ARRAY,ITEM1,ITEM2,...)
  • ARRAY is the array where given values will be pushed or added. This parameter is required.
  • ITEM single or multiple values will be added to the ARRAY. This parameter is required. VALUES can be single or multiple values separated by a comma. It can be also an array too.

The return value of the array_push() method is an integer that will return a new number of elements in the array.

Append/Add New Item Into Array

New items can be added to the array can be done by providing new items by separating them with commas.

<?php

   $names = array("ismail","ahmet");

   array_push($names,"elif");

?>

Single or more items can be specified to be added to the array.

<?php

   $names = array("ismail","ahmet");

   array_push($names,"elif","ali");

   print_r($names);

?>

The output will be like below where new items are added with index numbers 2 and 3.

Array
(
[0] => ismail
[1] => ahmet
[2] => elif
[3] => ali
)

We can also add another array into an existing array as an item like below. In the following example, we will add the $new_names array into the $names array as an item.

<?php

   $names = array("ismail","ahmet");

   $new_names = array("elif","ali");

   array_push($names,$new_names);

   print_r($names);

?>

The output will be like below where the $new_names array will be an item in the $names array.

Array
(
[0] => ismail
[1] => ahmet
[2] => Array
(
   [0] => elif
   [1] => ali
)
)

Append Arrays By Merging with array_merge()

PHP also provides the array_merge() function which will merge all provided arrays into a single array. The provided array items will be put into the new array. The syntax of the array_merge() function is like below.

array_merge(ARRAY1,ARRAY2,...)
  • ARRAY is single or more arrays that will be merged. Multiple arrays can be provided by separating them with a comma.

The return value will be a new array that contains all given ARRAY elements.

<?php

   $names1 = array("ismail","ahmet");

   $names2 = array("elif","ali");

   $new_names = array_merge($names1,$names2);

   print_r($new_names);

?>

The output will be like the below.

Array
(
    [0] => ismail
    [1] => ahmet
    [2] => elif
    [3] => ali
)

Leave a Comment