PHP Reference ยท Array Functions
PHP array_unshift() function
Reference for PHP array_unshift(): prepend one or more values to the start of an array, how keys are renumbered, return value and alternatives.
The array_unshift() function adds one or more values to the beginning of an array and returns the new number of elements. The values keep the order in which you pass them. The array is passed by reference, so it is changed in place.
All integer keys are renumbered from 0, and string keys are kept. Because every existing element has to move, it is slower than array_push() on large arrays.
$list = ["c", "d"]; array_unshift($list, "a", "b"); print_r($list); // ["a", "b", "c", "d"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_unshift(array &$array, mixed ...$values): int
| Name | Description |
|---|---|
$array |
The array to change, passed by reference. |
...$values |
Values to insert at the start, in the order given. |
Return value: the new number of elements in the array.
Errors / Exceptions: a TypeError if the first argument is not an array.
Usage notes
- Integer keys are renumbered, string keys are preserved. To prepend while keeping integer keys, build a new array with the
+operator:$new + $old. - Passing an array adds one nested element, not its contents. To prepend the contents of another array use
array_merge($other, $array). - Slow on large arrays. It is O(n) because every element moves. If you prepend often, consider
SplDoublyLinkedListor build the array in reverse and usearray_reverse()at the end. - Needs a variable, not a literal or a function result.
- Opposite operation:
array_shift()removes the first element.array_push()adds to the end. - Calling it with only the array is allowed since PHP 7.3 and changes nothing.
Related
array_shift(),array_push(),array_merge(),array_pop()- Lessons: Arrays, Array functions