When working with PHP arrays, you often need to add new elements to an existing collection. For example, you might want to add products to a list, register new tasks, or store items in a processing queue.
The array_push() function adds one or more elements to the end of an array. It also returns the array's new length.
What Is array_push() in PHP?
The array_push() function appends values to an existing array.
Its syntax is:
array_push(
array &$array,
mixed ...$values
): int
The parameters are:
$array— The array to modify....$values— One or more values to append.
The function returns the new number of elements in the array, not the added values.
Unlike functions that return a new array, array_push() modifies the original array directly.
Example 1: Adding a Single Element
Let's add another programming language to an existing list.
<?php
$languages = ["PHP", "Python"];
array_push($languages, "JavaScript");
print_r($languages);
Output:
Array
(
[0] => PHP
[1] => Python
[2] => JavaScript
)
The new value is placed at the end of the array.
For a single element, PHP also supports the shorter syntax $languages[] = "JavaScript";. This avoids the overhead of calling a function.
Example 2: Adding Multiple Elements
One advantage of array_push() is that it accepts several values in a single call.
<?php
$colors = ["Red", "Blue"];
$newCount = array_push(
$colors,
"Green",
"Yellow"
);
echo "Total elements: " . $newCount . PHP_EOL;
print_r($colors);
Output:
Total elements: 4
Array
(
[0] => Red
[1] => Blue
[2] => Green
[3] => Yellow
)
The function adds both values and returns 4, the total number of elements after the operation.
Since PHP 7.3, calling array_push($colors) without additional values is also valid. It leaves the array unchanged and returns its current length.
How Does array_push() Handle Array Keys?
New elements receive automatically assigned numeric keys, even when the existing array contains string keys.
<?php
$data = [
"status" => "Pending",
5 => "Existing"
];
array_push($data, "New");
print_r($data);
Output:
Array
(
[status] => Pending
[5] => Existing
[6] => New
)
The string key status and numeric key 5 remain unchanged. PHP assigns the appended element the next available automatic numeric index.
array_push() does not create custom string keys. Use direct assignment, such as $data["priority"] = "High";, when you need a named key.
Adding an Array as an Element
Passing an array as a value does not automatically merge its contents into the destination array.
<?php
$items = ["PHP"];
array_push($items, ["Python", "Go"]);
print_r($items);
Output:
Array
(
[0] => PHP
[1] => Array
(
[0] => Python
[1] => Go
)
)
The nested array is added as a single element.
To append its individual values instead, you can use argument unpacking: array_push($items, ...$newItems), where $newItems is an indexed array. Alternatively, use array_merge() when you want a new combined array.
Practical Example: Managing a Task Stack
A common application of array_push() is managing a stack, which follows the Last In, First Out (LIFO) principle.
New tasks are added with array_push(), and the most recently added task is removed with array_pop().
Create a file named task-stack.php:
<?php
declare(strict_types=1);
// Start with an empty stack.
$tasks = [];
// Add tasks.
array_push(
$tasks,
[
"id" => "TASK-101",
"title" => "Review article"
],
[
"id" => "TASK-102",
"title" => "Publish guide"
]
);
// Add another task.
array_push($tasks, [
"id" => "TASK-103",
"title" => "Update sitemap"
]);
echo "<h2>Processing Tasks</h2>";
echo "<ul>";
// Process newest tasks first.
while ($tasks !== []) {
$task = array_pop($tasks);
$message = $task["id"]
. ": "
. $task["title"];
echo "<li>" . htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
) . "</li>";
}
echo "</ul>";
Browser output:
Processing Tasks
TASK-103: Update sitemap
TASK-102: Publish guide
TASK-101: Review article
The newest task is processed first because array_pop() removes the last element.
This approach is useful for simple in-memory stacks, undo histories, and temporary task collections.
array_push() vs Related Functions
| Operation | Behavior |
|---|---|
array_push() |
Adds one or more elements to the end. |
$array[] = $value |
Appends one element using shorter syntax. |
array_unshift() |
Adds elements to the beginning. |
array_pop() |
Removes and returns the last element. |
Common Mistakes
- Expecting a new array: The function modifies the existing array and returns its length.
- Expecting nested arrays to expand: An array passed as one value becomes one element.
- Expecting string keys to be created: Appended elements receive numeric keys.
- Passing a non-array argument: The first argument must be an array, or PHP raises a
TypeErrorin PHP 8+. - Passing an expression instead of a variable: The first argument is passed by reference and must be a writable array variable.
Key Takeaways
array_push()appends one or more values to an existing array.- It modifies the original array directly.
- Its return value is the new number of elements.
- New elements receive automatically assigned numeric keys.
- Use
$array[] = $valuewhen appending a single value. - Combine
array_push()witharray_pop()to implement a stack.
The array_push() function provides a convenient way to append multiple values to PHP arrays. It is particularly useful when building collections dynamically and managing stack-based operations.
For additional details, see the official PHP array_push() documentation.