In this article, you will learn how to remove the first element from an array in PHP.
PHP array_shift() Function
In PHP, you can remove the first element of an array using the array_shift() function:
The array_shift() function takes the first element of an array and returns its value. This element is also removed from the original array. The function modifies the original array and returns the value of the removed element. If the array is empty, it returns NULL. array_shift re-indexes the remaining elements of the array so that the keys start from 0.
<?php $fruits = array("apple", "banana", "cherry", "orange"); $first_fruit = array_shift($fruits); echo $first_fruit . "\n"; print_r($fruits); ?>
This will output:
apple Array (  => banana  => cherry  => orange )
As you can see, the first element of the array $fruits has been removed, and its value (“apple”) has been returned and assigned to $first_fruit. The remaining elements have been re-indexed to start from 0.