What is the array_shift method in PHP?

We can use the array_shift method to remove the first element from an array.

Syntax

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 resetspoints to the first element of the array the internal pointer of the array.

Example

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

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources