Home >>PHP Array Functions >PHP array_unshift() Function
PHP array_unshift() function is used to add one or more elements into any given array. These elements are added at the beginning of the given array. All the elements are inserted to the array in the same order as they have been passed.
Syntax:
array_unshift(array, value1, value2, value3, ...);
Parameter | Description |
---|---|
array | This is a required parameter. This parameter defines the given array. |
value1 | This is an optional parameter. This parameter defines a value to insert. |
value2 | This is an optional parameter. This parameter defines another value to insert. |
value3 | This is an optional parameter. This parameter defines more values to insert. |
Here is an example of array_unshift() function in PHP:
<html> <body> <pre> <?php $x=array("M","A","N","Y","U"); array_unshift($x,"A","B","H","I"); print_r($x); ?> </pre> </body> </html>
Array ( [0] => A [1] => B [2] => H [3] => I [4] => M [5] => A [6] => N [7] => Y [8] => U )
Example 2:
<html> <body> <pre> <?php for($i=10;$i<=15;$i++) { $x[]=$i; } echo "Before the unshift(): <br>"; print_r($x); for($i=9;$i>=0;$i--) { array_unshift($x,$i); } echo "<br>After the unshift(): <br>"; print_r($x); ?> </pre> </body> </html>
Before the unshift(): Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 [4] => 14 [5] => 15 ) After the unshift(): Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 )