PHP array_shift

Summary: in this tutorial, you will learn how to use the PHP array_shift() function to remove an element from the beginning of an array.

Introduction to the PHP array_shift function #

The array_shift() function removes the first element from an array and returns it.

The following shows the syntax of the array_shift() function:

array_shift(array &$array): mixedCode language: PHP (php)

In this syntax, the $array is the input array from which you want to remove the first element.

If the $array is empty or is not an array, the array_shift() function returns null.

Note that the array_shift() function changes the input array by shortening it by one element. It also modifies numerical array keys so that the first element in the modified array has a key starting from zero.

To remove an element from the end of an array and return it, you use the array_pop() function.

PHP array_shift() function example #

The following example uses the array_shift() function to remove the first element of an array:

<?php

$numbers = [1, 2, 3];

$first_number = array_shift($numbers);

print_r($numbers);Code language: PHP (php)

Try it

Output:

Array
(
    [0] => 2
    [1] => 3
)Code language: PHP (php)

How it works.

  • First, define an array with three numbers 1, 2, and 3.
  • Second, remove the first element of the $numbers array and assign it to the $first_number variable.
  • Third, show the elements of the $numbers array.

The output indicates that the number of elements of the $numbers array is 2 after the removal. Additionally, its index also changes.

Since the array_shift() needs to reindex the array after removing the first element, the function will be pretty slow if the input array is large.

Removing elements from an associative array #

The following example shows how to use the array_shift() function to remove the first element of an associative array:

<?php

$scores = [
    "John" => "A",
    "Jane" => "B",
    "Alice" => "C"
];

$score = array_shift($scores);

echo $score . '<br>';
print_r($scores);Code language: PHP (php)

Try it

Output:

A
Array ( [Jane] => B [Alice] => C )Code language: PHP (php)

In this example, the array_shift() function removes the first element of the $scores array and returns the value of the element, which is "A". It also preserves the keys in the array.

Summary #

  • Use the PHP array_shift() function to remove an array from the beginning of an array and return it.
Did you find this tutorial useful?