array_push() / array_pop() / array_shift() / array_unshift() Since: PHP 4(2000)
Functions for adding and removing elements at the beginning or end of an array. Use these when you need stack or queue style data manipulation.
Syntax
// Adds one or more elements to the end of an array. array_push(array, value1, value2, ...); // Removes and returns the last element of an array. array_pop(array); // Removes and returns the first element of an array. array_shift(array); // Adds one or more elements to the beginning of an array. array_unshift(array, value1, value2, ...);
Function List
| Function | Description |
|---|---|
| array_push($array, $value, ...) | Adds one or more elements to the end of an array. Returns the new number of elements in the array. |
| array_pop($array) | Removes and returns the last element of an array, shortening the array by one. |
| array_shift($array) | Removes and returns the first element of an array. The remaining elements are reindexed starting from zero. |
| array_unshift($array, $value, ...) | Adds one or more elements to the beginning of an array. Returns the new number of elements in the array. |
Sample Code
<?php $fruits = ['apple', 'orange', 'grape']; // Add elements to the end. array_push($fruits, 'peach', 'strawberry'); print_r($fruits); // Results in ['apple', 'orange', 'grape', 'peach', 'strawberry']. // Remove the last element. $last = array_pop($fruits); echo $last; // Outputs 'strawberry'. // Remove the first element. $first = array_shift($fruits); echo $first; // Outputs 'apple'. // Add elements to the beginning. array_unshift($fruits, 'melon', 'watermelon'); print_r($fruits); // Results in ['melon', 'watermelon', 'orange', 'grape', 'peach']. // You can also use $fruits[] to append to the end. $fruits[] = 'banana'; print_r($fruits); // 'banana' is added to the end.
Notes
array_push() and array_pop() operate on the end of an array, while array_unshift() and array_shift() operate on the beginning. By combining these, you can implement stack and queue behavior.
When you only need to append a single element, the $array[] = $value syntax is simpler and faster. Use array_push() when you want to add multiple values at once.
When array_shift() is called, the remaining numeric keys are re-indexed starting from zero. String keys are preserved, so be aware of key changes when using it with associative arrays. To manipulate elements at an arbitrary position, use array_splice().
If you find any errors or copyright issues, please contact us.