PHP Program to insert element into an array at specified position

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 are first assigning value into the array arr[] and after that, we have to assign the new 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 new variable. And at last, we can print the elements of the array arr[] by using foreach loop.  

Syntax of array_splice() function


array_splice(array, start, length, array)
 

ALGORITHM

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 with parameters array_splice(arr, pos,0,newValue)

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

PHP Source Code

                                          <?php
$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 ";
}
?>
                                      

OUTPUT

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