Skip to content
Advertisement

How to insert element into arrays at specific position?

Let’s imagine that we have two arrays:

JavaScript

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

Advertisement

Answer

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

JavaScript

This example:

JavaScript

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement