PHP program to add item at the beginning of associative array



To add an item at the beginning of the associative array, the code is as follows−

Example

 Live Demo

<?php    $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );    echo "Initial Array...
";    print_r($arr);    array_unshift($arr,"100");    echo "Updated Array...
";    print_r($arr); ?>

Output

This will produce the following output−

Initial Array... Array(    [p] => 150    [q] => 100    [r] => 120    [s] => 110    [t] => 115    [u] => 103    [v] => 105    [w] => 125 ) Updated Array... Array (    [0] => 100    [p] => 150    [q] => 100    [r] => 120    [s] => 110    [t] => 115    [u] => 103    [v] => 105    [w] => 125 )

Example

Let us now see another example−

 Live Demo

<?php    $arr = array( 0=>"Ryan", 1=>"Kevin", 2=>"Jack" );    echo "Initial Array...
";    print_r($arr);    array_unshift($arr,"Katie");    echo "Updated Array...
";    print_r($arr); ?>

Output

This will produce the following output−

Initial Array... Array(    [0] => Ryan    [1] => Kevin    [2] => Jack ) Updated Array... Array(    [0] => Katie    [1] => Ryan    [2] => Kevin    [3] => Jack )
Updated on: 2019-12-26T10:15:13+05:30

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements