How to Use array_shift in PHP: Syntax and Examples
In PHP,
array_shift removes the first element from an array and returns it, shifting all other elements down by one. It modifies the original array by reference and returns null if the array is empty.Syntax
The array_shift function takes one parameter: the array you want to modify. It removes the first element and returns it. The array is changed directly.
- array_shift(array &$array): mixed
- $array: The input array passed by reference.
- Returns the removed first element or
nullif the array is empty.
php
array_shift(array &$array): mixed
Example
This example shows how array_shift removes the first element from an array and returns it. The original array is changed after the call.
php
<?php $fruits = ['apple', 'banana', 'cherry']; $first = array_shift($fruits); echo "Removed element: $first\n"; echo "Remaining array: "; print_r($fruits); ?>
Output
Removed element: apple
Remaining array: Array
(
[0] => banana
[1] => cherry
)
Common Pitfalls
Common mistakes include:
- Passing a non-array variable causes a warning.
- Expecting
array_shiftto return the array without the first element (it returns only the removed element). - Not realizing the original array is changed.
- Using
array_shifton an empty array returnsnull.
php
<?php // Wrong: expecting array_shift to return the array without first element $numbers = [1, 2, 3]; $newArray = array_shift($numbers); // $newArray is 1, not the array // Right: use array_shift to get first element, then use $numbers $first = array_shift($numbers); // $numbers now has [2, 3] ?>
Quick Reference
| Function | Description | Returns | Modifies Original Array |
|---|---|---|---|
| array_shift | Removes first element from array | Removed element or null if empty | Yes |
Key Takeaways
array_shift removes and returns the first element of an array, modifying the original array.
If the array is empty, array_shift returns null.
Always pass a valid array to avoid warnings.
array_shift returns the removed element, not the modified array.
The original array keys are reindexed after removal.