insert an element into an array at a specific index in php

To insert a new element into a PHP array at a specific index, you can use the array_splice() function. This built-in PHP function allows you to add, remove, and replace array elements at specific positions.

Here's an example of how to insert an element at a specified index in a PHP array:

main.php
// create an array
$array = array('apple', 'banana', 'orange');

// insert a new element at index 1
$new_element = 'pear';
array_splice($array, 1, 0, $new_element);

// output the updated array
print_r($array);
211 chars
10 lines

This would output: Array ( [0] => apple [1] => pear [2] => banana [3] => orange )

In this example, we first create an array with three elements. We then define a new variable $new_element to hold the value we want to insert.

We then call array_splice() and pass in the array we want to modify, the index at which we want to insert the new element (in this case, index 1), the number of elements to remove from that position (in this case, 0, since we just want to insert), and the new element we want to add.

Finally, we output the updated array to verify that the new element has been added at the designated index.

gistlibby LogSnag