How to add an element to an array at the first position in Twig
When using the merge function in Twig, the new element is appended to the array. However, we would like the new element to prepend the existing array.
{# The elements array we want to add a '0' to at the beginning. #}
{% set elements = ['1', '2', '3'] %}
{# Working: Merge elements to a new array and override the variable. The result will be ['0', '1', '2', '3']. #}
{% set elements = ['0']|merge(elements) %}
{# Not working: The result will be ['1', '2', '3', '0']. #}
{% set elements = elements|merge(['0']) %}
Issue:
When using the merge function in Twig, the new element is appended to the array. However, we would like the new element to prepend the existing array.
Solution:
Create a new array and append the original array to it.
Ihre Drupal-Website zukunftssicher machen
Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.