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.

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,VALUES)
  • ARRAY is the array where given values will be pushed or added. This parameter is required.
  • VALUES single or multiple values which will be added into the ARRAY. This parameter is required. VALUES can be a single or multiple values separated with comma. It can be also an array too.

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

Append/Add New Item Into Array

New items can be added into the array can be done by providing new items by separating them with comma.

<?php

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

array_push($names,"elif");

?>

Single or more items can be specified to be added into 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 number 2 and 3.

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

We can also add another array into 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 sinle array. The provided arrays 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 which 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 below.

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

Leave a Comment