PHP array_shift() Function
Quick summary: The PHP array_shift() function removes the first element from an array and returns it.
PHP array_shift() Syntax
array_shift(array &$array): mixed
PHP
PHP array_shift() Basic examples
$queue = [1,2,3];
$first = array_shift($queue);
var_dump($first);
print_r($queue);
PHP
Output:
int(1) and Array ( [0] => 2 [1] => 3 )
Removes and returns the first element; numeric keys are reindexed.
PHP array_shift() Real-world usage
$tasks = ['task1','task2','task3'];
$current = array_shift($tasks);
echo $current;
PHP
Output:
task1
Implements queue (FIFO) behavior.
PHP array_shift() Edge cases
$empty = [];
var_dump(array_shift($empty));
PHP
Output:
NULL
Returns null if the array is empty.
PHP array_shift() Common mistakes
Expecting keys to be preserved
Numeric keys are reindexed after shifting.
Incorrect
$a = [10=>1, 20=>2];
array_shift($a);
print_r($a);
Correct
// Use unset() if you need to preserve keys
array_shift() reindexes numeric keys automatically.
PHP array_shift() Frequently Asked Questions
What does array_shift() do?
Removes and returns the first element of an array.
Does array_shift() modify the array?
Yes, it reindexes the array.
Use case?
Queue-like operations.
Return value?
First element or null.
Common mistake?
Ignoring reindexing.
Performance?
Slower on large arrays.
Alternative?
array_slice().
Handles empty array?
Returns null.
Safe?
Yes.
Preserves keys?
No.
Best practice?
Avoid on large arrays.
Used in queues?
Yes.