PHP Function Reference

PHP array_unshift() Function



The PHP array_unshift() function inserts passed values to the beginning of an array. All numerical array keys is modified to start counting from zero while string keys remains unaffected.

Syntax

array_unshift(array, values)

Parameters

array Required. Specify the input array.
values Required. Specify the values to insert to the beginning of the array.

Return Value

Returns the new number of elements in the array.

Exceptions

NA.

Example:

The example below shows the usage of array_unshift() function.

<?php
$Arr = array(10, 20, 30);

//displaying the array
print_r($Arr);
echo "\n";

//inserting values at the
//beginning of the array
array_unshift($Arr, -10, 0);

//displaying the array
print_r($Arr);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

Array
(
    [0] => -10
    [1] => 0
    [2] => 10
    [3] => 20
    [4] => 30
)

Example:

Consider one more example where array_unshift() function is used with an associative array. Please note that, here the string keys remains unaffected.

<?php
$Arr = array("Marry"=>25, 
             "John"=>30, 
             "Jo"=>45);

//displaying the array
print_r($Arr);
echo "\n";

//inserting values at the
//beginning of the array
array_unshift($Arr, "Red", "Blue", "Green");

//displaying the array
print_r($Arr);
?>

The output of the above code will be:

Array
(
    [Marry] => 25
    [John] => 30
    [Jo] => 45
)

Array
(
    [0] => Red
    [1] => Blue
    [2] => Green
    [Marry] => 25
    [John] => 30
    [Jo] => 45
)

❮ PHP Array Reference