PHP array_push() Function

Quick summary: The PHP array_push() function adds one or more elements to the end of an array.

PHP array_push() Syntax

array_push(array &$array, mixed ...$values): int
PHP

PHP array_push() Basic examples

$stack = [1,2];
array_push($stack, 3);
print_r($stack);
PHP
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )

Adds a single element to the end of the array.

$stack = [1];
array_push($stack, 2, 3);
print_r($stack);
PHP
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )

Adds multiple elements at once.

PHP array_push() Real-world usage

$log = [];
array_push($log, 'Start process');
print_r($log);
PHP
Output:
Array ( [0] => Start process )

Append log entries dynamically.

PHP array_push() Edge cases

$array = [];
$count = array_push($array, 'a');
var_dump($count);
PHP
Output:
int(1)

Returns the new number of elements in the array.

PHP array_push() Common mistakes

Using array_push() for single value unnecessarily

Using $array[] = $value is faster and cleaner.

Incorrect
array_push($array, 'value');
Correct
$array[] = 'value';

Prefer bracket syntax for single element insertion.

PHP array_push() Frequently Asked Questions

What does array_push() do?

Adds one or more elements to the end of an array.

Use case?

Appending values.

Return value?

New length of array.

Common mistake?

Using instead of [].

Modifies array?

Yes.

Performance?

Slightly slower than [].

Supports multiple values?

Yes.

Safe?

Yes.

Alternative?

$arr[].

Handles empty array?

Yes.

Used in stacks?

Yes.

Best practice?

Prefer [] syntax.

PHP array_push() Related PHP Functions