PHP array unshift

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.

Pictorial Presentation :

php array array_unshift() function

Example :

  1. $fruits_list = array('Orange',  'Apple');  

  2. array_unshift($fruits_list, 'Banana', 'Cherry');  

  3. print_r($fruits_list);  

  4. ?>  

Output :

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