How to insert element into arrays at specific position?

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

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

For your first array, use array_splice():

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

array_splice($array_1, 3, 0, 'more');
print_r($array_1);

output:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)

for the second one there is no order so you just have to do :

$array_2['more'] = '2.5';
print_r($array_2);

And sort the keys by whatever you want.

Tags:

Php

Arrays