This post will discuss how to insert an item at a specific position in an array in PHP.

1. Using array_slice() function

A simple solution to insert an item at a specific position in an array is using the array_slice() function. The idea is to extract a slice of the array using array_slice() function and then recombine the parts using the array_merge() function.

The following code demonstrates this:

Download  Run Code

 
For associative arrays,

Download  Run Code

 
For associative arrays, we can also use the union operator (+) to recombine the parts, which appends the right-hand array to the left-hand array.

Download  Run Code

 
Note that for a normal array where the keys are integer, + operator might not work as expected.

2. Using array_splice() function

Another solution is to use array_splice() function, which removes a portion of the array and replace it with the elements of the specified array.

Download  Run Code

 
Note that array_splice() does not preserve numeric keys. Consider the following example, which is trying to splice an associative array with numeric keys using array_splice() function.

Download  Run Code

That’s all about inserting an item at a specific position in an array in PHP.