PHP array_push: Add Elements to End of Array
In PHP, adding elements to the end of an array is a fundamental task
easily accomplished using the built-in array_push()
function. This article provides a direct guide on how to use
array_push() to append one or multiple values to an
existing array, explains its syntax, and highlights a common, faster
alternative for adding single elements.
How array_push() Works
The array_push() function treats an array as a stack and
pushes the passed variables onto the end of that array. The length of
the array increases by the number of variables pushed.
Syntax
array_push(array &$array, mixed $value1, mixed $... = ?): int$array: The input array. This is passed by reference, meaning the function modifies the original array directly.$value1, $...: The values to push onto the end of the array.- Return Value: Returns the new number of elements in the array.
Code Examples
1. Adding a Single Element
To add one element to the end of an array:
$fruits = ["apple", "banana"];
array_push($fruits, "cherry");
print_r($fruits);Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
2. Adding Multiple Elements
You can push multiple elements at once by passing them as additional arguments:
$colors = ["red", "green"];
array_push($colors, "blue", "yellow", "purple");
print_r($colors);Output:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => yellow
[4] => purple
)
Alternative: Using
the Square Bracket Syntax []
If you are only adding a single element to an array, it is
recommended to use the square bracket syntax
($array[] = $value) instead of array_push().
This method is cleaner and faster because it does not have the overhead
of calling a function.
$fruits = ["apple", "banana"];
$fruits[] = "cherry"; // Equivalent to array_push($fruits, "cherry")Use array_push() primarily when you need to add multiple
elements to an array at the same time.