How to remove first element from an array in PHP?

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.

Returns Value

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.

For example: Using string elements

snippet
<?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.

Output
Arraylist: Array ( [0] => Blue [1] => Red [2] => Black [3] => Green [4] => Gray [5] => White ) Removed element from array is: Blue Updated arraylist: Array ( [0] => Red [1] => Black [2] => Green [3] => Gray [4] => White )

Example: Using numeric keys

snippet
<?php
	$game = array(1 => "Carom", 2 => "Chess", 3 => "Ludo");
	echo "Removed element: ".array_shift($game). "</br>";
	print_r($game);
?>

Output

Output
Removed element: Carom Array ( [0] => Chess [1] => Ludo )

Example: Using numeric values

snippet
<?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 25 is removed from the first position in the given array, and updated list is displayed below.

Output
Removed array element is: 25 Update array is: Array ( [0] => 12 [1] => 65 2] => 37 [3] => 95 [4] => 38 [5] => 12 )
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents