PHP: How to Insert a Value at the Front of an Array CodeUnit 12 SEP 2011

To add or insert a value into the front of a standard array using PHP is actually pretty simple thanks to the nifty little array_unshift function. (If you think about it, it does exactly the opposite of PHP’s array_shift function!)

In practice:

//declare an array to test on
$arr = array('apple','pear');

//right, now add 'peaches' to the front of the array

//you can even push multiple items onto the front of the array

The array’s internal numeric index gets automatically renumbered in case you are wondering, meaning that $arr[0] will now point to the last item prepended to the array.


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.