How to use array_shift() function In PHP

The array_shift() function removes the first element from an array and returns it. This function also re-indexes the array so that the keys start from 0 again.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php

    $arr = array(1, 2, 3, 4, 5, 6);
    $removedElement = array_shift($arr);
    echo "Removed element: " . $removedElement . "\n";

    echo "Updated array: ";
    print_r($arr);
?>

Output
Removed element: 1
Updated array: Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)

Remove First Element from an Array in PHP

Given an array, the task is to remove the first element from an array in PHP.

Examples:

Input: arr = [1, 2, 3, 4, 5, 6, 7];
Output: 2, 3, 4, 5, 6, 7

Input: arr = [3, 4, 5, 6, 7, 1, 2]
Output: 4, 5, 6, 7, 1, 2

Below are the methods to remove the first element from an array in PHP:

Table of Content

  • Using array_shift() function
  • Using array_slice() function
  • Using unset() Function

Similar Reads

Using array_shift() function

The array_shift() function removes the first element from an array and returns it. This function also re-indexes the array so that the keys start from 0 again....

Using array_slice() function

The array_slice() function is used to extract a portion of an array. By specifying a start index of 1, you can extract all elements except the first one....

Using unset() Function

TheĀ unset() function is usedĀ to remove the first element from an array. This function takes the array and the index of the element to be removed as arguments....

Contact Us