$output=array_unshift($input);
array_unshift()
total elements of the array increases by one or more . All numerical array keys are re-indexed but literal keys remain same.
$input=array('One','Two','Three','Four','Five');
$output=array_unshift($input,'added_now');
echo $output; // Output is 6
echo "<br><br>";
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output of above code is here( $output gets the number of elements present 6 )
6
0 -> added_now
1 -> One
2 -> Two
3 -> Three
4 -> Four
5 -> Five
To add more than one element we will change the code like this.
$output=array_unshift($input,'added_one','add_two');
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$output=array_unshift($input, 'Strawberry');
echo $output; // Output is 5
echo "<br><br>";
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output is here, ( $output gets the first element Banana)
5
0 -> Strawberry
Fruits1 -> Banana
Fruits2 -> Mango
Fruits3 -> Apple
Fruits4 -> Grapes
Now key of the first element is 0. To add one element with key to an associative array we have to use the code below.
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$input=array('new_fruit'=> 'Strawberry') + $input;
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output is here
new_fruit -> Strawberry
Fruits1 -> Banana
Fruits2 -> Mango
Fruits3 -> Apple
Fruits4 -> Grapes
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
echo current($input);
echo "<br>";
$output=array_unshift($input,'Strawberry');
echo current($input);
Output is here.( The first element is changed from Banana to Mango)
Banana
Strawberry
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.