PHP 8 reference · Array Functions
PHP array_unshift() Function
Add one or more elements to the start of an array and return its new length. Numeric keys are renumbered.
PHP 8 Since 4.0
Syntax
array_unshift(array &$array, mixed ...$values): int
Parameters
| Parameter | Description |
|---|---|
array |
The array (changed in place). |
values |
The values to prepend, kept in this order. |
Return value
The new number of elements.
Examples
<?php
$list = ["c", "d"];
array_unshift($list, "a", "b");
print_r($list);
Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)<?php
$crumbs = ["Docs", "Arrays"];
array_unshift($crumbs, "Home");
echo implode(" > ", $crumbs), "\n";
Output
Home > Docs > Arrays
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
| PHP 7.3 | Can be called with only the array argument. |
In other languages
list.insert()· Pythonarray.unshift()· JavaScript
Related
array_shift()· Remove the first element of an array and return it. Numeric keys are renumbered from 0; string keys stay.array_push()· Add one or more elements to the end of an array and return its new length. $array[] = $value does the same for one value.array_merge()· Merge one or more arrays into a new array. Numeric keys are renumbered; for string keys the later value wins.- PHP Arrays · tutorial
- PHP Array Functions · tutorial