array_unshift()

array_unshift() — Prepend one or more elements to the beginning of an array.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

Signature

array_unshift(array &$array, mixed ...$values): int

Parameters

ParameterTypeWhat it takes
&$arrayarrayThe input array.
...$valuesmixedThe values to prepend.

Return value

Returns the new number of elements in the array.

Example

A runnable snippet:

$queue = [ "orange", "banana" ]; array_unshift($queue, "apple", "raspberry"); var_dump($queue);

Output:

array(4) { [0]=> string(5) "apple" [1]=> string(9) "raspberry" [2]=> string(6) "orange" [3]=> string(6) "banana" }

Changelog

VersionChange
7.3.0This function can now be called with only one parameter. Formerly, at least two parameters have been required.

See also

array_merge(), array_shift(), array_push(), array_pop()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_unshift() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.