PHP program to add item at the beginning of associative array

In PHP, you can add an item at the beginning of an associative array using the array_unshift() function. However, this function resets numeric keys and converts the array to indexed format for new elements.

Using array_unshift() with String Keys

When using array_unshift() on an associative array with string keys, the new element gets a numeric index ?

<?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); ?>
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
)

Using array_unshift() with Numeric Keys

With numeric keys, array_unshift() reorders all existing keys and adds the new element at index 0 ?

<?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); ?>
Initial Array...
Array(
    [0] => Ryan
    [1] => Kevin
    [2] => Jack
)
Updated Array...
Array(
    [0] => Katie
    [1] => Ryan
    [2] => Kevin
    [3] => Jack
)

Alternative Method: Array Union Operator

To preserve associative keys when adding at the beginning, use the array union operator with a new key ?

<?php
    $arr = array( "p"=>"150", "q"=>"100", "r"=>"120" );
    echo "Initial Array...
"; print_r($arr); $arr = array("new"=>"999") + $arr; echo "Updated Array...
"; print_r($arr); ?>
Initial Array...
Array(
    [p] => 150
    [q] => 100
    [r] => 120
)
Updated Array...
Array(
    [new] => 999
    [p] => 150
    [q] => 100
    [r] => 120
)

Conclusion

Use array_unshift() for simple prepending, but be aware it resets numeric keys. For preserving associative structure, use the array union operator with a new key−value pair.

Updated on: 2026-03-15T08:20:33+05:30

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements