The array_unshift function inserts new values to the beginning of the array. In the case of the array with numeric keys, the newly inserted elements are assigned the numeric keys starting from 0 and increment by 1. However, string keys remain the same.
What is the syntax of the array_unshift function in PHP?
array_unshift(array, value1, value2, value3, ...)
Parameter | Description |
---|---|
array | The array to insert new values to – Required |
value1 | Value to insert – Optional |
value2 | Next value to insert – Optional |
value,… | More values to insert – Optional |
Examples of array_unshift function
Example 1. Insert new values in an array with string keys.
<?php
$arr=array("a"=>"R","b"=>"G");
print_r(array_unshift($arr,"B"));
?>
Example 2. Insert new values in an array with numeric keys.
<?php
$arr=array(0=>"R",1=>"G");
array_unshift($arr,"B");
print_r($arr);
?>