w3resource

PHP: array_unshift() function

PHP: Prepend one or more elements to the beginning of an array

The array_unshift() is used to add one or more elements to the beginning of an array.

Note: 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.

Version:

(PHP 4 and above)

Syntax:

array_unshift(array1,value1,value2......valuen )

Parameters:

Name Description Required /
Optional
Type
array1 The specified array. Required Array
value1 Element to be added. Required Mixed*
value2..n Elements to be added Optional Mixed*

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value

The new number of elements in array1.

Value Type : Integer.

Example:

<?php
$fruits_list = array('Orange',  'Apple');
array_unshift($fruits_list, 'Banana', 'Cherry');
print_r($fruits_list);
?>

Output:

Array ( [0] => Banana [1] => Cherry [2] => Orange [3] => Apple) 

Pictorial Presentation:

php function reference: array_unshift() function

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: array_unique
Next: array_values



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php/function-reference/array_unshift.php