Say for example an array variable is being sent to a twig template from a symfony application and it has duplicated values in it. In this example, it will be processed in twig template to create a new array variable without duplicated records.


Duplicated array


# This has been passed from symfony application
$cars = ['bmw', 'mercedes', 'audi', 'toyota', 'bmw', 'audi', 'mazda'];

# Print it in twig template
{{ dump(cars) }}

# Output in twig template
array:7 [
0 => "bmw"
1 => "mercedes"
2 => "audi"
3 => "toyota"
4 => "bmw"
5 => "audi"
6 => "mazda"
]

Array reduce


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

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

Result


bmw mercedes audi toyota mazda