Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

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