How to insert an element at a specific index in an array with PHP

1 Answer

0 votes
$array = [4, 9, 8, 6, 5, 7];

$index = 2;
$element = 100;

// Insert the element at the specified index
array_splice($array, $index, 0, $element);

print_r($array);



/*
run:

Array
(
    [0] => 4
    [1] => 9
    [2] => 100
    [3] => 8
    [4] => 6
    [5] => 5
    [6] => 7
)

*/

 



answered Feb 20, 2025 by avibootz

Related questions

...