We can use the array_shift
method to remove the first element from an array.
array_shift(array)
This method returns the value of the first element. If the array is empty, then null
is returned.
Upon removing the first element, the numeric index of all elements is reassigned, starting from zero. Non-numeric keys remain unchanged.
This method
the internal pointer of the array. resets points to the first element of the array
<?php$numbers = [1,2,'three' => 3,4];echo "The array is ";print_r($numbers);echo "\n";echo "Removing first element: ". array_shift($numbers). "\n";echo "After deleting first element the numeric index of array will be changed. \nThe array is ";print_r($numbers);echo "\n";echo "Removing first element: ". array_shift($numbers). "\n";echo "Removing first element: ". array_shift($numbers). "\n";echo "Removing first element: ". array_shift($numbers). "\n";echo "Removing first element: ";var_dump(array_shift($numbers));echo "\nThe array is ";print_r($numbers);?>
In the code above:
We created a numbers
array.
We used the array_shift
method multiple times and removed the first element of the array until the array becomes empty.