Master PHP’s array_shift(): Remove and Retrieve the First Array Element
Learn how PHP’s array_shift() function removes and returns the first element of both indexed and associative arrays, updates the original array’s keys, and see practical code examples demonstrating its usage and output.
PHP is a widely used scripting language especially suited for web development. Among its powerful array functions is array_shift(), which 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 ) Here $array is the array to be operated on, passed by reference.
Example with an indexed array:
$fruits = array("apple", "banana", "orange", "grape");
$firstFruit = array_shift($fruits);
echo "First fruit: " . $firstFruit . "<br>";
echo "Remaining fruits:";
print_r($fruits);Output:
First fruit: apple
Remaining fruits: Array ( [0] => banana [1] => orange [2] => grape )The function pops the first element "apple" from $fruits into $firstFruit and updates $fruits so that its remaining elements are re‑indexed.
Note that array_shift() returns the value of the first element and also reindexes the original array.
It works the same way with associative arrays. Example:
$person = array(
"name" => "John",
"age" => 25,
"gender" => "male"
);
$firstProperty = array_shift($person);
echo "First property: " . $firstProperty . "<br>";
echo "Remaining properties:";
print_r($person);Output:
First property: John
Remaining properties: Array ( [age] => 25 [gender] => male )In associative arrays, array_shift() removes and returns the value of the first key‑value pair while preserving the remaining keys. array_shift() is a practical PHP array function that efficiently removes the first element from both indexed and associative arrays, returning the value and updating the original array, helping developers write cleaner and more efficient code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
