PHP Function Reference

PHP array_push() Function



The PHP array_push() function is used to insert one or more elements to the end of an array. The function treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.

Note: To add an element to the array, it is better to use $array[] = because in this way there is no overhead of calling a function.

Syntax

array_push(array, value1, value2, ...)

Parameters

array Required. Specify an array.
value1, value2, ... Optional. Specify the values to push onto the end of the array.

Return Value

Returns the new number of elements in the array.

Exceptions

NA.

Example:

In the example below, array_push() function is used to add elements in the given array.

<?php
$Arr = array(10, 20);

//adding single element
array_push($Arr, 30);

//adding multiple elements
array_push($Arr, 40, 50);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)

Example:

The example below shows the usage of array_push() function with an associative array.

<?php
$Arr = array("A"=>10, "B"=>20);

//add elements in the array
array_push($Arr, 30, 40);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [A] => 10
    [B] => 20
    [0] => 30
    [1] => 40
)

❮ PHP Array Reference