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 Instance

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 better to use $array[] = to add a single element to an array with string keys using array_push(), because it does not have the extra burden 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 Instance