PHP Reference ยท Array Functions
PHP array_shift() function
Reference for PHP array_shift(): remove and return the first element of an array, how integer keys are renumbered, empty arrays and queue patterns.
The array_shift() function removes the first element of an array and returns it. The array is passed by reference and becomes one element shorter. Integer keys of the remaining elements are renumbered starting from 0; string keys are kept.
Use it to take items from the front, such as processing a queue of jobs or peeling the command name off a list of arguments.
$args = ["git", "commit", "-m"]; $command = array_shift($args); // "git" print_r($args); // ["commit", "-m"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_shift(array &$array): mixed
| Name | Description |
|---|---|
$array |
The array to change, passed by reference. |
Return value: the removed first value, or null if the array was empty.
Errors / Exceptions: a TypeError if the argument is not an array.
Usage notes
- Integer keys are renumbered from 0. String keys stay. This is the main difference from
unset($a[array_key_first($a)]), which leaves the other keys alone. - It is O(n). Every remaining element has to be moved down, so draining a large array with
array_shift()in a loop gets slow. For big queues useSplQueue, or keep an index and read$array[$i++]. nullis ambiguous. An empty array and a first element that isnullboth returnnull; the loop in the first example stops at a storednullfor the same reason.- Needs a variable, not a literal or a function result.
- To read without removing, use
reset($array)or$array[array_key_first($array)]. - Opposite operations:
array_unshift()adds to the front,array_pop()removes the last element. - Pointer reset: the array's internal pointer is reset after the call.