20

In PHP I would do this:

foreach( $array as $key => $value ) {

    echo $another_array[$key];

}

I can't see how to do that in Twig (in Symfony2). I've tried various things, but this would seem the obvious answer, but it doesn't work. It returns a 'Item "the_index" for "Array" does not exist in' error.

{% for value in array %}

    {% set the_index = loop.index %}
    {{ another_array.the_index }}

Any ideas?

3 Answers 3

43

The fastest way:

{% for key,value in array %}
  {{ another_array[key] }}
{% endfor %}
1
  • 1
    Great. I used that to compose the element name of a dynamically generated form. form_row(form["element_#{element.id}"]) Mar 1, 2018 at 9:41
31

You can use the attribute function.

{{ attribute(another_array, the_index) }}
1
<ul>
    {% for value in array %}
       {% set the_index = attribute(another_array,  loop.index) %}
       <li>{{ the_index }}</li>
    {% endfor %}
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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