BentCoder BentCoder - 25 days ago 12
Twig Question

Creating an array within for loop with Twig

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 %}

Answer

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.

Comments