21

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

Great. I used that to compose the element name of a dynamically generated form. form_row(form["element_#{element.id}"])
32

You can use the attribute function.

{{ attribute(another_array, the_index) }}

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.