The array_shift() function in PHP is used to remove the first element from an array and return it. The array keys are re-indexed after the shift, and the array is modified in place.
Syntax:
array_shift(array &$array): mixed
- $array: The input array, passed by reference.
- Return value: The first element of the array, or
NULLif the array is empty.
Example 1: Basic usage
$array = [1, 2, 3, 4, 5];
$shifted = array_shift($array);
echo "Shifted element: " . $shifted . "\n"; // Output: 1
print_r($array); // Output: [2, 3, 4, 5]
In this example:
- The first element (
1) is removed from the$array. - The shifted element (
1) is returned. - The remaining array becomes
[2, 3, 4, 5].
Example 2: With an associative array
$array = ["a" => "apple", "b" => "banana", "c" => "cherry"];
$shifted = array_shift($array);
echo "Shifted element: " . $shifted . "\n"; // Output: apple
print_r($array); // Output: Array ( [b] => banana [c] => cherry )
- The first element (
apple) is removed. - The remaining array has re-indexed keys (
bandc).
Example 3: Empty array
$array = [];
$shifted = array_shift($array);
echo "Shifted element: " . ($shifted ? $shifted : "None") . "\n"; // Output: None
- When the array is empty,
array_shift()returnsNULL.
Example 4: Working with numeric keys
$array = [10, 20, 30, 40];
$shifted = array_shift($array);
echo "Shifted element: " . $shifted . "\n"; // Output: 10
print_r($array); // Output: [20, 30, 40]
- The first element (
10) is removed, and the array is re-indexed.
Key Points:
- The array is modified directly (passed by reference).
- The array keys are re-indexed after the shift, so the keys of remaining elements are adjusted accordingly.
- The function returns the value of the shifted element or
NULLif the array is empty.
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
