Open In App

How to Remove First Element from an Array in PHP?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an Array, the task is to remove the first element from the array in PHP. There are three methods to remove the first element from an array, these are – using array_shift(), array_slice(), and unset() functions. Let’s explore each method with detailed explanations and code examples.

Approach 1: Using array_shift() Function

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

PHP
<?php

$arr = array(10, 20, 30, 40, 50, 60);

$removedElement = array_shift($arr);

echo "Removed element: " . $removedElement . "\n";

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

?>

Output
Removed element: 10
Updated array: Array
(
    [0] => 20
    [1] => 30
    [2] => 40
    [3] => 50
    [4] => 60
)

Approach 2: Using array_slice() Function

The array_slice() function is used to extract a slice of an array. By specifying the start index as 1, you can remove the first element from the array.

PHP
<?php

$arr = array(10, 20, 30, 40, 50, 60);

$updated_array = array_slice($arr, 1);

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

?>

Output
Updated array: Array
(
    [0] => 20
    [1] => 30
    [2] => 40
    [3] => 50
    [4] => 60
)

Approach 3: Using unset() Function

You can also use the unset() function to remove the first element from an array. This function takes the array and the index of the element to be removed as arguments.

PHP
<?php

$arr = array(10, 20, 30, 40, 50, 60);

unset($fruits[0]);

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

?>

Output
Updated array: Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
    [5] => 60
)

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads