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: HTML, XML (xml)

Output:

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

How it works.

  • First, define an array that has 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.

As you can see clearly from the output, the $numbers array is changed from 3 elements to 2 elements. In addition, the indexes of the $numbers array are also changed.

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

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?