PHP Program to insert element into an array at specified position

It is a simple array program in PHP using an array, loop, and in-built function. Let's go through these topics to understand this program clearly

What is an array and how to insert elements to it?

An array is a data structure consisting of a collection of elements, each identified by at least one array index or key. The Elements are of the same data type.

To insert an element into an array we need an index or position where it is to be placed because elements are fetched using array index only. To add an element to the end of an array is easy but we need shifting of elements to insert an element in between of array. PHP provides an in-built function to insert elements, let's make use of it in our program.

How to insert into the array at a certain position using PHP?

In this program, we are going to insert an element at a specified index. For that, we first declare and assign values into the array arr[]. After that, we need a new value that is going to insert into the array, assign a value into the variable newValue. Then we have to specify the position where we have to insert the new element and assign that value into the variable pos. And to insert the element we are using the built-in function array_splice(). In the function, we specify the array arr[], the position of the element in variable pos, and the newValue. And at last, we can print the elements of the array arr[] by using foreach loop.  

Syntax of array_splice() function

array_splice(src_array, start_index, length, replace_array)

The array_splice() function removes selected elements of size length from start_index of an array src_array and replaces them with new elements given in replace_array . The function also returns an array with the removed elements. 

NOTE: The function does not remove any elements (if length= 0), the replace_array will be inserted from the position of the start_index parameter.


Step 1: Initialize an array arr[] with values

Step 2: Print the element currently in the array arr[] using foreach loop

Step 3: Assign the new value to be inserted to the variable newValue

Step 4: Assign the position of the element to be inserted into the variable pos

Step 5: Call the built-in function array_splice(arr, pos,0,newValue)

Step 6: Print the elements in the array arr[] using foreach loop

PHP Source Code

$arr = array(1, 2, 3, 4, 5);
echo "Array before inserting new element: \n";
foreach ($arr as $x) {
    echo "$x ";
$newValue = 23;
$pos = 2;
array_splice($arr, $pos, 0, $newValue);
echo "\nArray after inserting new element: \n";
foreach ($arr as $x) {
    echo "$x ";


Array before inserting new element:
1 2 3 4 5
Array after inserting new element:
1 2 23 3 4 5