Loop through nested array in Twig I have created a variable to use in my twig template. The variable consists of a nested array. If I dump the variable I get the following result:


dump(gallery_images)
array (size=2)
  'img' => 
    array (size=15)
      0 => 'path-to-file.jpeg'
      1 => 'path-to-file.jpeg'
      .....
   'alt' =>
    array (size=15)
      0 => 'img 1 alt text'
      1 => 'img 2 alt text'


I want to loop through gallery_images and map the alt text to the image. My loop was working fine before I added the nested array / alt text. This is how I expected it to work:

{% for gallery_image in gallery_images %}
  &lt;li&gt;
      &lt;img src="{{ gallery_image.img }}" alt="{{ gallery_image.alt }}" /&gt;
  &lt;/li&gt;
{% endfor %}


That did not work, then I tried to call the src and alt with 

{{ gallery_image.0 }}
{{ gallery_image.1 }}


Then I only got 1 file and 1 alt text. What is the correct way to loop through the nested array? Also bear in mind I may want to add title text next.
Do you have control over your array structure? 

Why not just change it to this:

[
  0 =&gt; ['alt' =&gt; 'alt text', 'img' =&gt; 'image-path'],
  1 =&gt; ...?
]


Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with {% for key, path in gallery_images.img %} and use the key toaccess gallery_iamges.alt[key]` (not 100% sure about the exact syntax). Certainly more complicated that way.