Using PHP array_shift() to Remove the First Element from an Array

This article explains the PHP array_shift() function, shows its syntax, demonstrates how it removes and returns the first element of both indexed and associative arrays, and highlights that the original array is re‑indexed after the operation.

php Courses
php Courses
php Courses
Using PHP array_shift() to Remove the First Element from an Array

PHP is a widely used scripting language especially suited for web development, and it provides many powerful array functions, one of which is array_shift(). This function removes and returns the first element of an array while updating the original array’s keys.

The syntax of array_shift() is: mixed array_shift ( array &$array ) In the following example, $fruits is an indexed array. After calling array_shift($fruits), the first fruit "apple" is stored in $firstFruit and the remaining elements are re‑indexed.

$fruits = array("apple", "banana", "orange", "grape");
$firstFruit = array_shift($fruits);

echo "第一个水果是:".$firstFruit."<br>";
echo "剩余的水果有:";
print_r($fruits);

Output:

第一个水果是:apple
剩余的水果有:Array ( [0] => banana [1] => orange [2] => grape )

The function also works with associative arrays. In the next example, $person is an associative array; array_shift($person) returns the value of the first key‑value pair ("John") and removes that pair from the array.

$person = array("name" => "John", "age" => 25, "gender" => "male");
$firstProperty = array_shift($person);

echo "第一个属性是:".$firstProperty."<br>";
echo "剩余的属性有:";
print_r($person);

Output:

第一个属性是:John
剩余的属性有:Array ( [age] => 25 [gender] => male )

In both cases, array_shift() not only returns the first element’s value but also updates the original array, causing its indexes to be re‑ordered starting from zero.

Overall, array_shift() is a very useful PHP array function for efficiently removing the first element of an array, whether it is a simple indexed array or an associative array.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Arrayassociative arrayphp-functionsarray_shift
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.