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.


About Craig Lotter

Software developer, husband and dad to two young ladies. Writer behind An Exploring South African. I don't have time for myself any more.