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
NULL
if 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 (
b
andc
).
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
NULL
if the array is empty.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.