PHP array_push() Function

Example

Insert "blue" and "yellow" at the end of the array:

<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>

Run Instances

Definition and Usage

The array_push() function adds one or more elements (pushes) to the end of the array specified by the first parameter and then returns the length of the new array.

This function is equivalent to multiple calls to $array[] = $value.

Tips and Notes

Note:Even if the array has string keys, the elements you add are always numeric keys. (See Example 2)

Note:It is more efficient to use $array[] = instead of array_push() to add a single element to an array, as it does not incur the overhead of calling a function.

Note:If the first parameter is not an array, array_push() will issue a warning. This is different from the behavior of $var[], which will create a new array.

Syntax

array_push(array,value1,value2...)
Parameters Description
array Required. Specify the array.
value1 Required. Specify the value to be added.
value2 Optional. Specify the value to be added.

Technical Details

Return Value: Returns the number of elements in the new array.
PHP Version: 4+

More Examples

Example 1

Array with String Keys:

<?php
$a=array("a"=>"red","b"=>"green");
array_push($a,"blue","yellow");
print_r($a);
?>

Run Instances