PHP Adding element to start of array


Example

Sometimes you want to add an element to the beginning of an array without modifying any of the current elements (order) within the array. Whenever this is the case, you can use array_unshift().

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Taken from the PHP documentation for array_unshift().

If you'd like to achieve this, all you need to do is the following:

$myArray = array(1, 2, 3);

array_unshift($myArray, 4);

This will now add 4 as the first element in your array. You can verify this by:

print_r($myArray);

This returns an array in the following order: 4, 1, 2, 3.

Since array_unshift forces the array to reset the key-value pairs as the new element let the following entries have the keys n+1 it is smarter to create a new array and append the existing array to the newly created array.

Example:

$myArray = array('apples', 'bananas', 'pears');
$myElement = array('oranges');
$joinedArray = $myElement;

foreach ($myArray as $i) {
  $joinedArray[] = $i;
}

Output ($joinedArray):

Array ( [0] => oranges [1] => apples [2] => bananas [3] => pears ) 

Eaxmple/Demo