W3docs

Twig for loop for arrays with keys

To loop through an array with keys in Twig, you can use the for loop and access the key and value of each element in the array using the loop variable.

To loop through an array with keys in Twig, you can use the for loop and access the key and value of each element in the array using the loop variable. For example:

Loop through an array with keys

{% for key, value in array %}
    Key: {{ key }} Value: {{ value }}
{% endfor %}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also use the key and value variables to access the current key and value within the loop. For example:

Access keys and values inside the loop

{% for key, value in array %}
    Key: {{ key }} Value: {{ value }}
    {# do something with key and value #}
{% endfor %}

Note: Twig provides built-in loop variables like loop.index, loop.first, and loop.last that you can use to track iteration state or apply conditional styling.

You can also use the keys and values filters to get the keys and values of an array separately. This is useful when you only need one part of the pair, though the standard for key, value in array syntax is generally preferred for paired access.

Use keys and values filters

{% for key in array|keys %}
    Key: {{ key }}
{% endfor %}

{% for value in array|values %}
    Value: {{ value }}
{% endfor %}