array_unshift()
Learn how PHP array_unshift() prepends elements to the start of an array, re-indexes numeric keys, and returns the new count — with examples.
Are you looking for a powerful function to add new elements to the beginning of an array in PHP? Look no further than the array_unshift() function. With this function, you can easily add one or more elements to the beginning of an array, automatically re-indexing numeric keys and shifting existing elements to higher positions.
What is array_unshift()?
The array_unshift() function is a built-in PHP function that adds one or more elements to the beginning of an array. It does not replace existing elements — it shifts them to higher index positions to make room for the new ones. Think of it as the mirror image of array_push(), which appends to the end.
Syntax
array_unshift(array &$array, mixed ...$values): int$array— the array to prepend to. It is passed by reference, so the original variable is modified in place.$values— one or more values to add to the front. Listed left to right, they appear in the same order at the start of the array.
The function returns the new number of elements in the array (an integer), not the array itself.
Basic example
We add "orange" and "lemon" to the front of $fruits. The numeric keys are re-indexed automatically starting from 0, and the return value 5 is the new element count. The output is:
5
Array
(
[0] => orange
[1] => lemon
[2] => apple
[3] => banana
[4] => cherry
)How keys are handled
This is the most common source of surprises. array_unshift() treats numeric and string keys differently:
- Numeric keys are reset. All existing integer keys are renumbered starting from
0. Any custom integer keys you set are lost. - String (associative) keys are preserved. Only the newly prepended elements receive numeric keys (
0,1, …); existing string keys keep their names.
<?php
$data = array("name" => "Alice", 10 => "ten", 20 => "twenty");
array_unshift($data, "first");
print_r($data);
?>Output — note "name" stays, but 10 and 20 become 1 and 2:
Array
(
[0] => first
[name] => Alice
[1] => ten
[2] => twenty
)When to use it
- Building a queue or list where new items belong at the front (most recent first).
- Adding a header row or default value before existing data.
- Reversing the effect of
array_shift(), which removes the first element.
A note on performance: because every existing element must be reindexed and shifted, array_unshift() is O(n) — slower than array_push(), which is O(1). For very large arrays inside a hot loop, prefer pushing and reversing once at the end, or use a structure such as SplDoublyLinkedList.
Related functions
array_push()— add elements to the end of an array.array_shift()— remove the first element.array_splice()— insert or remove elements at any position.array_merge()— combine two or more arrays.