Skip to content
Tutorials Center
My learning

Topics

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.

PHP
$args = ["git", "commit", "-m"];
$command = array_shift($args); // "git"
print_r($args);                // ["commit", "-m"]

Try it

PHP Taking items from the front

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.

PHP Renumbering of keys

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

PHP
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 use SplQueue, or keep an index and read $array[$i++].
  • null is ambiguous. An empty array and a first element that is null both return null; the loop in the first example stops at a stored null for 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.