Array Functions

PHP array_unshift() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_unshift() function inserts one or more elements at the beginning of an array.

All numerical array keys will be modified to start counting from zero. String keys will remain the same.

The following table summarizes the technical details of this function.

Return Value: Returns the new number of elements in the array.
Changelog: Since PHP 7.3.0 this function can now be called with only one parameter (i.e. array). Previously, at least two parameters have been required.
Version: PHP 4+

Syntax

The basic syntax of the array_unshift() function is given with:

array_unshift(array, value1, value2, ...);

The following example shows the array_unshift() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue");

// Prepending two values to the colors array
array_unshift($colors, "yellow", "orange");
print_r($colors);
?>

Parameters

The array_unshift() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
value1, value2, ... Optional. Specifies the values to prepend to the beginning of the array.

More Examples

Here're some more examples showing how array_unshift() function actually works:

You can also prepend values to the associative arrays as demonstrated below:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Prepending a single value to the alphabets array
array_unshift($alphabets, "elephant");
print_r($alphabets);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties