PHP
π€ PHP array_shift() Function: Removing the First Element
The array_shift() function in PHP shifts the first value of the array off and returns it, shortening the array by one element and moving everything down.
-
Return Value:
array_shift()returns the removed value. If the array is empty or not an array, it returnsnull.
π οΈ Basic Syntax & Usage
Pass an array variable to array_shift() to remove its beginning element:
PHP
$queue = ["First Task", "Second Task", "Third Task"];
// Shift the first element off the beginning
$currentTask = array_shift($queue);
echo "Processing: " . $currentTask; // Outputs: Processing: First Task
print_r($queue);
/*
Output:
Array
(
[0] => Second Task
[1] => Third Task
)
*/
π Queue (FIFO) Operations with PHP
Combining array_push() and array_shift() allows you to easily implement a standard First-In, First-Out (FIFO) queue structure in PHP.
PHP
$customerQueue = [];
// Customers join queue
array_push($customerQueue, "John");
array_push($customerQueue, "Sarah");
// Serve first customer in line (Shift first item)
$servedCustomer = array_shift($customerQueue); // "John"
echo "Served: " . $servedCustomer;
echo " Next in line: " . $customerQueue[0]; // "Sarah"
π Key Rules & Behaviors
-
1. Index Re-indexing: All numerical keys will be modified to start counting from zero (
0), while literal string keys will remain untouched. - 2. Direct Mutation: The function directly modifies the target array variable passed into it by reference.
-
3. Empty Array Handling: Calling
array_shift()on an empty array safely returnsnullwithout producing errors.
π Array Beginning/End Removal Comparison
| Function | Target Position | Key Re-indexing | Common Data Structure |
|---|---|---|---|
array_pop() |
End of array | No (Keys stay as they are) | Stack (LIFO) |
array_shift() |
Beginning of array | Yes (Numeric keys reset from 0) | Queue (FIFO) |
-
π Short Summary
-
array_shift()removes and returns the first element from an array. - It automatically updates numeric keys so the remaining elements re-index starting from 0.
-
Use
array_shift()along witharray_push()to handle FIFO queues.
