Adding element to start of array

suggest change

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**.

array_unshift() reindexes numeric keys: the new element gets key 0, and the following entries get keys n+1. String keys are left unchanged. To build the same list of values yourself, create a new array and append the existing values:

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 )

Example/Demo

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents