Thursday, 25 September 2014

array_unshift in PHP

array_unshift() Function is used to insert new elements to the beginning of an input array.

Syntax:

array_unshift(array,value1,value2,value3...)
 
Parameters Description: 
array : Required. Specifying an array
value1 : Required. Specifies a value to insert
value2 : Optional. Specifies a value to insert
value3 : Optional. Specifies a value to insert

Tip : You can add one value, or as many as you like.
Note : Numeric keys will start at 0 and increase by 1. String keys will remain the same

Example:

<?php
$daysarr1 = array( "a"=>"Sunday","b"=>"Monday" );
array_unshift($daysarr1,"Tuesday");
print_r($daysarr1);
$daysarr1 = array( "a"=>"Sunday","b"=>"Monday" );
echo "<br />"."using return value";
print_r(array_unshift($daysarr1,"Tuesday"));
$daysarr1 = array( 0=>"Sunday",1=>"Monday" );
echo "<br />"."using numeric keys";
array_unshift($daysarr1,"Tuesday");
print_r($daysarr1);
?>

O/P:

Array (
         [0] => Tuesday 
         [a] = > Sunday
         [b] => Monday 
        )
using return value 
3
using numeric keys Array ( 
          [0] => Tuesday
          [1] = > Sunday
          [2] => Monday
          )

0 comments:

Post a Comment