You are here

array_push()

Submitted by Peter on Fri, 2005-07-01 00:00

The PHP function array_push() is an expansion of an existing PHP feature. array_push($x, 'a'); does exactly the same as $x[] = 'a'; and is slower because PHP has to perform extra overheads for functions. If you want to do anything other than add a single value to an array then array_push() has advantages.

If you add a single item to the end of an array, always use code of the form $x[] = 'a'; instead of array_push($x, 'a');.

Array creation

You can create an array using the following code which creates an empty array named $x. This array creation technique will create the array if the array does not exist and will replace a variable with an array if the variable exists.
$x = array();

You can create an array containing one or more entries by using the following code. This example creates an array named $x containing three entries.
$x = array('a', 'b', 'c');

You can create an array containing one entry by using the following code, which creates an array named $x. This method of array creation can add only one entry to an existing array and creates the array if the array does not yet exist.>
$x[] = 'a';

You cannot create an array using array_push(). array_push() returns an error from the following code.
array_push($y, 'a');
warning: array_push() [function.array-push]: First argument should be an array

Multiple Values

array_push() accepts multiple values. Start with an example where array $x exists and you want to add three entries. The following code might have the first line, the creation of $x, at the start of a script. The three lines to add entries might be at a later point in the script.
$x = array('a');
$x[] = 'b';
$x[] = 'c';
$x[] = 'd';

You could add three entries to $x using the following array_merge().
$x = array('a');
$x = array_merge($x, array('b', 'c', 'd'));

The following code uses array_push() to add the entries to $x with less complexity than array_merge().
$x = array('a');
array_push($x, 'b', 'c', 'd');

Number of Entries in the Array

array_push() returns the number of entries in the array. The following code returns the value three.
$x = array();
print(array_push($x, 'a', 'b', 'c'));

$x = array();
print(array_push($x, 'a', 'b', 'c')); ?>

The following code returns the value five.
$y[] = 'something';
$y[] = 'more stuff';
print(array_push($y, 'a', 'b', 'c'));

$y[] = 'something';
$y[] = 'more stuff';
print(array_push($y, 'a', 'b', 'c')); ?>

Wrong Parameter Count Error

What happens if we do not add anything to the array. Does array_push() return the count for the array or produce an error? The following code creates an array containing one value, then uses array_push() to add nothing, and produces an error.
$y = array('a');
array_push($y);

warning: Wrong parameter count for array_push()