PHP array_shift: Remove the First Element of an Array
This article provides a quick guide on how to use the
array_shift() function in PHP to remove and return the
first element of an array. You will learn the syntax, see a practical
code example, and understand how the function modifies array keys and
handles empty inputs.
The array_shift() function shifts the first value of the
array off and returns it, shortening the array by one element.
Syntax of array_shift()
array_shift(array &$array): mixed$array: The input array. This array is passed by reference, meaning the function directly modifies the original variable.- Return Value: Returns the removed value, or
nullif the array is empty.
Code Example
Here is a straightforward example demonstrating how to remove the first element and assign it to a variable:
<?php
$fruits = ["apple", "banana", "cherry"];
// Remove and return the first element
$first_fruit = array_shift($fruits);
// Output the removed element
echo "Removed Element: " . $first_fruit . "\n";
// Output: Removed Element: apple
// Output the modified array
print_r($fruits);
/*
Output:
Array
(
[0] => banana
[1] => cherry
)
*/
?>Key Behaviors of array_shift()
- Direct Modification: Because
array_shift()takes the array by reference, the original array is modified directly. You do not need to reassign the function output back to the array. - Key Reindexing: Numerical keys in the array are automatically reindexed starting from zero. Literal (string) keys, however, are preserved and remain unchanged.
- Handling Empty Arrays: If you pass an empty array
to
array_shift(), the function will returnnullwithout throwing an error.