array_unshift
Prepends elements to the beginning of an array.
Syntax
array_unshift(array &$array, mixed ...$values): intParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being modified. |
| ...$values | mixed | The values to prepend. |
Return value
intThe new number of elements.
Examples
An element at the start of a list:
<?php
$steps = ['cook', 'eat'];
array_unshift($steps, 'buy');
echo implode(' > ', $steps);Output:
buy > cook > eatSeveral values keep their order:
<?php
$numbers = [3];
array_unshift($numbers, 1, 2);
echo implode(', ', $numbers);Output:
1, 2, 3Notes
Numeric keys are renumbered from zero, string keys stay as they were.
See also
- array_shift — Removes the first element of an array and returns it.
- array_push — Appends elements to the end of an array.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.