Open In App

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:

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.

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

<?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
)

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.

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

<?php

    $arr = array(1, 2, 3, 4, 5, 6);

    $arr = array_slice($arr, 1);

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

?>

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

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.

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

<?php

    $arr = array(1, 2, 3, 4, 5, 6);

    unset($arr[0]);
    $arr = array_values($arr); // Re-index the array

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

?>

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

Article Tags :