Master PHP’s array_shift(): Remove and Retrieve the First Array Element Efficiently

This article explains PHP’s array_shift() function, showing its syntax, how it removes and returns the first element of both indexed and associative arrays, updates the original array’s keys, and provides clear code examples with expected output.

php Courses
php Courses
php Courses
Master PHP’s array_shift(): Remove and Retrieve the First Array Element Efficiently

PHP is a widely used scripting language, especially suitable for web development. Among its many powerful array functions, array_shift() can remove and return the first element from the beginning of an array while updating the array’s keys.

The syntax of the function is: mixed array_shift ( array &$array ) Here $array is the array to be operated on and is passed by reference.

Example with a simple indexed array:

$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 pops the first element "apple" into $firstFruit and updates $fruits to contain only the remaining elements.

Note that array_shift() not only returns the first element’s value but also reindexes the original array’s keys.

Example with an associative 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 associative arrays, array_shift() works the same way: it removes and returns the value of the first key‑value pair and updates the array.

Summary

The array_shift() function is a very useful PHP array function that conveniently removes and returns the first element from the start of an array while updating the array’s keys. It works correctly for both ordinary and associative arrays, allowing developers to write cleaner and more efficient code.

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.

Backend DevelopmentPHPreferencearray functionsassociative arrayarray_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.