HOW to insert an element into arrays at a specific position?

array_slice() PHP function can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$numbers = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'four' => '4',
);

$final_numbers = array_slice($numbers, 0, 3, true) + array("three" => "3") + array_slice($array, 3, count($array) - 1, true) ;

The final result will be

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
Scroll to Top