To remove the first element or value from an array, array_shift() function is used. This function also returns the removed element of the array and returns NULL if the array is empty. After removing first element, the key of the other elements is modified, and again array is numbered from beginning, only if the keys are numerical.
It is an inbuilt array function of PHP, which shifts an element from the beginning of the array.
The array_shift() function, which is used to remove the first element from an array, returns the removed element. It also returns NULL, if the array is empty.
<?php $color = array("Blue", "Red", "Black", "Green", "Gray", "White"); echo "Arraylist: "; print_r($color); $remove = array_shift($color); echo "</br>Removed element from array is: "; print_r($remove); echo "</br> Updated arraylist: "; print_r($color); ?>
Output
An element "Blue" is removed from the first position in the given array, and updated list is displayed in the given output.
Example: Using numeric keys
<?php $game = array(1 => "Carom", 2 => "Chess", 3 => "Ludo"); echo "Removed element: ".array_shift($game). "</br>"; print_r($game); ?>
Output
Example: Using numeric values
<?php $numbers = array(25, 12, 65, 37, 95, 38, 12); $removed = array_shift($numbers); echo "Removed array element is: ". $removed; echo "</br> Update array is: "; print_r($numbers); ?>
Output
An element