Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_push() function

Reference for PHP array_push(): append one or more values to the end of an array, what it returns, how it compares to $a[] = and why it needs a variable.

The array_push() function appends one or more values to the end of an array. The array is passed by reference, so it is changed in place, and the function returns the new number of elements.

For a single value, the short form $array[] = $value does the same job without a function call and is the more common choice. array_push() earns its place when you add several values at once, or when you need a callable (for example, as a callback name).

PHP
$stack = [1, 2];
array_push($stack, 3, 4);
print_r($stack); // [1, 2, 3, 4]

Try it

PHP Pushing values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP String keys are untouched, new keys are numeric

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_push(array &$array, mixed ...$values): int
Name Description
$array The array to change, passed by reference. It must be a variable (or another writable expression such as $this->items).
...$values Zero or more values to append, in the order given.

Return value: the new number of elements in the array.

Errors / Exceptions: passing something that is not an array throws a TypeError. If the next integer key would overflow (the array already uses PHP_INT_MAX), an Error is thrown.

Usage notes

  • Prefer $array[] = $value for one element. It avoids a function call and reads more naturally.
  • New elements get integer keys continuing after the largest existing integer key. String keys stay as they are.
  • Pushing an array adds a nested array, not its elements. To append the elements of another array use array_merge() or the spread operator: array_push($a, ...$b).
  • The array must be a variable. A literal or a function result cannot be passed by reference.
  • Calling it with only the array is allowed since PHP 7.3 and does nothing except return the count.
  • Order matters: array_push($a, 1, 2) appends 1 and then 2.
  • Opposite operation: array_pop() removes the last element. To add at the front use array_unshift().
  • Not for non-arrays: objects implementing ArrayAccess or SplStack have their own methods.