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