PHP array_unshift() Function

Example

Insert the element "blue" into the array:

<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");;
print_r($a);
?>

Run Instance

Definition and Usage

The array_unshift() function is used to insert new elements into the array. The value of the new array will be inserted at the beginning of the array.

The elements added will be added as a whole, and the order of these elements in the array will be the same as the order in the parameters.

This function will return the number of elements in the array.

Tip:You can insert one or more values.

Note:Numeric keys will start from 0 and increment by 1. String keys will remain unchanged.

Syntax

array_unshift(array,value1,value2,value3...)
Parameter Description
array Required. Specify the array.
value1 Required. Specify the value to be inserted.
value2 Optional. Specify the value to be inserted.
value3 Optional. Specify the value to be inserted.

Technical Details

Return value: Returns the number of new elements in the array.
PHP Version: 4+

More Examples

Example 1

Display returned value:

<?php
$a=array("a"=>"red","b"=>"green");
print_r(array_unshift($a,"blue"););
?>

Run Instance

Example 2

Use numeric keys:

<?php
$a=array(0=>"red",1=>"green");
array_unshift($a,"blue");;
print_r($a);
?>

Run Instance