This post will discuss how to insert items at the beginning of an array in PHP.

1. Using array_unshift() function

A simple and efficient solution is to use the array_unshift() function, which prepends one or more elements to the beginning of an array while maintaining the order of the prepended elements.

Following is a simple example demonstrating usage of this function for numerical key array:

Download  Run Code

 
Note that the numerical keys in the array are re-indexed starting with zero. However, the literal keys won’t be changed, as demonstrated below:

Download  Run Code

2. Using array_splice() function

Alternatively, you can use the array_splice() function, which replaces a part of an array with the elements of the specified array.

Here’s an example of its usage to insert an element at the specified position in an array:

Download  Run Code

 
Note that, like array_unshift() function, array_splice() does not preserve numeric keys.

Download  Run Code

3. Using + operator

In some cases, the above functions do not work since they always re-index the array. If you need to prepend an item to an array without re-indexing the keys or need to prepend a key-value pair to an associative array, you can + operator:

Download  Run Code

 
This however creates a new array and doesn’t modify the array in-place.

4. Using array_reverse() function

Another plausible way to insert an item at the beginning of an associative array is to reverse the array, insert a key and value pair using the $arr[$key] = $val syntax, and then reverse it back to get the desired order.

This approach is demonstrated below:

Download  Run Code

 
Like the + operator, this doesn’t modify the array in-place and creates a new array instead.

That’s all about inserting items at the beginning of an array in PHP.