How to Use array_push in PHP: Syntax and Examples
Use
array_push in PHP to add one or more elements to the end of an array. It takes the array as the first argument and the values to add as the following arguments, modifying the original array.Syntax
The array_push function adds one or more elements to the end of an array. It modifies the original array and returns the new number of elements in the array.
- array: The array to which you want to add elements.
- value1, value2, ...: One or more values to add to the array.
php
int array_push(array &$array, mixed ...$values)
Example
This example shows how to add multiple values to an existing array using array_push. The original array is updated with new elements at the end.
php
<?php $fruits = ["apple", "banana"]; array_push($fruits, "orange", "grape"); print_r($fruits); ?>
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => grape
)
Common Pitfalls
Common mistakes when using array_push include:
- Passing a non-array variable as the first argument causes an error.
- Expecting
array_pushto return the updated array instead of the new count. - Using
array_pushunnecessarily when you can add elements with$array[] = value;.
php
<?php // Wrong: passing a string instead of an array $string = "hello"; // array_push($string, "world"); // This will cause an error // Right: use an array $array = ["hello"]; array_push($array, "world"); print_r($array); ?>
Output
Array
(
[0] => hello
[1] => world
)
Quick Reference
| Function | Description | Return Value |
|---|---|---|
| array_push | Adds one or more elements to the end of an array | New number of elements in the array |
| $array[] = value; | Adds a single element to the end of an array | The assigned value |
Key Takeaways
Use array_push to add one or more elements to the end of an existing array.
array_push modifies the original array and returns the new count of elements.
You can also add a single element with $array[] = value; which is simpler and faster.
Always ensure the first argument to array_push is an array to avoid errors.
array_push is useful when adding multiple elements at once.