10

I'm trying to create an array and store values in it within for loop but failed so far. How can I do it with Twig?

I've read these but being new in Twig makes it hard to convert into my case.

PLAIN PHP LOGIC IS THIS:

foreach ($array as &$value)
{
   $new_array[] = $value;
}

foreach ($new_array as &$v)
{
   echo $v;
}

WHAT I'VE TRIED WITH TWIG:

{% for value in array %}
    {% set new_array = new_array|merge([value])  %}
{% endfor %}

{% for v in new_array %}
   {{ v }}
{% endfor %}
2
  • 3
    It is OK if you define the new_array as array before the first loop: {% set new_array = [] %}. Commented Jun 4, 2014 at 17:05
  • 8
    Twig is a wrong place to define your application logic Commented Jun 4, 2014 at 17:23

2 Answers 2

27

Solved by following Vision's suggestion:

{% set brands = [] %}
{% for car in cars %}
    {% if car not in brands %}
        {% set brands = brands|merge([car]) %}
    {% endif %}
{% endfor %}

{% for brand in brands %}
   {{ brand }}
{% endfor %}

Also I'll take bartek's comment into consideration next time. This was one off.

Sign up to request clarification or add additional context in comments.

Comments

1

I have other solution for arrays in loop. This solution is letting you to make arrays like PHP:

$my_array[] = array('key_1' => $value1, 'key_2' => $value_2);

in this case:

{% set cars_details = [] %}
{% for car in cars %}
     <!-- This is the line of code that does the magic -->
    {% set car = car|merge({(loop.index0) : {'color': car.color, 'year': car.year} }) %}
{% endfor %}
{{ car|dump }}

3 Comments

Have you revised your code to check if it is working? It is more confusing than solving problem.
@Vishal Kumar Sahu You'r right, I will have to recheck my answer.
I like how it creates a very specific array! Thanks!

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.