Kirzilla Kirzilla - 6 months ago 11
PHP Question

How to insert element into arrays at specific position?

Let's imagine that we have two arrays:

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

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


Now, I'd like to insert
array('sample_key' => 'sample_value')
after third element of each array. How can I do it?

Answer
$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
)
Comments