Add the element “blue” to the beginning of an array.
| <?php $a=array(“a”=>“red”,“b”=>“green”); array_unshift($a,“blue”); print_r($a); ?> |
The array_unshift() function adds new elements to the beginning of an array.
Tip: You can insert a single value or multiple values.
Note: Numeric keys will start at 0 and increment by 1, while string keys will remain unchanged.
| array_unshift(array, value1, value2, value3, …) |
|
Parameter |
Description |
|
array |
Required. Providing an array. |
|
value1 |
Optional. Specifies a value to insert (required in PHP versions prior to 7.3). |
|
value2 |
Optional. Specifies the value(s) to insert. |
|
value3 |
Optional. Specifies the value to be inserted. |
|
Return Value: |
Returns the updated number of elements in the array. |
|
PHP Version: |
4+ |
|
PHP Changelog: |
PHP 7.3: This function can now be called with just the array parameter. |
Display the return value.
| <?php $a=array(“a”=>“red”,“b”=>“green”); print_r(array_unshift($a,“blue”)); ?> |
Using numeric indices:
| <?php $a=array(0=>“red”,1=>“green”); array_unshift($a,“blue”); print_r($a); ?> |