Is it possible to insert items into specific positions in an array (rather than at the beginning or at the end), a bit like javascript splice? Say, if I wanted to add a value between items 2 and 3? Please note I want to add keys to the array rather than replace anything.

2 Answers 2


You can accomplish this with slice and merge, although it's not very pretty:

{% set myArray = ['a', 'b', 'd' ] %}
{% set myArray = myArray|slice(0,2)|merge(['c'])|merge(myArray|slice(2,myArray|length)) %}

{{ myArray|join(', ') }}

To explain what's happening above:

{% set myArray = ['a', 'b', 'd' ] %}

This just sets an array we can work with.


The first slice filter "chops off" and returns the first two items in the original array (namely "a" and "b"). We do this because we want to add a value after the "b" (i.e. the second index).


The first merge filter appends the value we want to add – the letter "c" – to the first two items. As merge is only able to merge arrays, we need to wrap the c in another array.


The inner part of this statement – the slice – pulls all the remaining values from the original array after the first two that we chopped off at the beginning, until the end of the array.

These values are then appended to the a, b and c with another merge statement.

{{ myArray|join(', ') }}

This is just a test, and will print a, b, c, d.

  • This worked thanks. Took me a while to get it, and had to break it down into shorter arrays and then join them altogether, as I wanted to add 4 and it was getting complicated! Hopefully this won't have too many implications performance-wise.
    – Anna
    Commented Oct 8, 2015 at 15:41
  • @Anna Happy you got it sorted! Twig quickly gets fairly unreadable when things gets a little complex – I added a more detailed explanation to my answer. Commented Oct 8, 2015 at 21:26

Do you render the content of your array right after you inserted the elements? Yes? Then what about using a conditional checking the loop.index in your output loop to render your special inserted content at defined loop positions?

{% if loop.index == 2 %}
{% endif %}
{% if loop.index in [2, 5, 13] %}
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.