PHP
How to Remove the First Element from a PHP Array
Efficiently remove and retrieve the first element from a PHP array using `array_shift()`, automatically re-indexing numeric keys as elements are shifted left.
<?php
$queue = ['task A', 'task B', 'task C'];
$first_task = array_shift($queue);
echo "Removed: " . $first_task . "
";
print_r($queue);
// Output:
// Removed: task A
// Array
// (
// [0] => task B
// [1] => task C
// )
$associative_data = [
'user_id' => 1,
'username' => 'john.doe',
'email' => '[email protected]'
];
$first_item = array_shift($associative_data);
echo "Removed first item from associative array: " . $first_item . "
";
print_r($associative_data);
// Output:
// Removed first item from associative array: 1
// Array
// (
// [username] => john.doe
// [email] => [email protected]
// )
// What if the array is empty?
$empty_array = [];
$result = array_shift($empty_array);
var_dump($result); // Output: NULL
?>
How it works: The `array_shift()` function removes the first element from an array and returns its value. The array's length is reduced by one, and all numeric keys of the remaining elements are re-indexed to start from 0. String keys, however, remain unchanged. If the array is empty, `array_shift()` returns `NULL`. This function is often used to process items from a queue or stack-like data structure.