Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_unshift

Prepends elements to the beginning of an array.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array being modified.
...$valuesmixedThe 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 > eat

Several values keep their order:

<?php
 
$numbers = [3];
array_unshift($numbers, 1, 2);
 
echo implode(', ', $numbers);

Output:

1, 2, 3

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.