How to Use array_unshift in PHP: Syntax and Examples
Use
array_unshift in PHP to add one or more elements to the start of an array. It modifies the original array and returns the new number of elements in the array.Syntax
The array_unshift function adds one or more elements to the beginning of an array. It takes the array as the first argument (passed by reference) and one or more values to add as the following arguments.
- array: The array to modify.
- value1, value2, ...: One or more values to add at the start.
The function returns the new length of the array after adding the elements.
php
int array_unshift(array &$array, mixed ...$values)
Example
This example shows how to add elements to the beginning of an array using array_unshift. The original array is changed, and the function returns the new count of elements.
php
<?php $fruits = ['banana', 'apple']; $newCount = array_unshift($fruits, 'orange', 'grape'); print_r($fruits); echo "New count: $newCount"; ?>
Output
Array
(
[0] => orange
[1] => grape
[2] => banana
[3] => apple
)
New count: 4
Common Pitfalls
Common mistakes when using array_unshift include:
- Expecting it to return the modified array instead of the new count.
- Passing the array by value instead of by reference, which means the original array won't change.
- Using it on non-array variables, which causes errors.
Always remember array_unshift changes the original array directly.
php
<?php // Wrong: expecting returned array $numbers = [2, 3]; $result = array_unshift($numbers, 1); var_dump($result); // int(3), not the array // Correct: check the array itself print_r($numbers); ?>
Output
int(3)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Quick Reference
| Function | Description | Returns |
|---|---|---|
| array_unshift | Adds elements to the start of an array | New number of elements in the array |
| Parameters | First: array by reference; then one or more values to add | — |
| Effect | Modifies the original array directly | — |
Key Takeaways
array_unshift adds one or more elements to the beginning of an array and modifies it directly.
The function returns the new total number of elements, not the modified array.
Always pass the array variable itself; it is changed by reference.
Use array_unshift to prepend items efficiently without creating a new array.