Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Filters merge
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x. 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

merge

The merge filter merges sequences and mappings:

For sequences, new values are added at the end of the existing ones:

1
2
3
4
5
{% set values = [1, 2] %}

{% set values = values|merge(['apple', 'orange']) %}

{# values now contains [1, 2, 'apple', 'orange'] #}

For mappings, the merging process occurs on the keys; if the key does not already exist, it is added but if the key already exists, its value is overridden:

1
2
3
4
5
{% set items = {'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown'} %}

{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}

{# items now contains {'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car'} #}

Tip

If you want to ensure that some values are defined in a mapping (by given default values), reverse the two elements in the call:

1
2
3
4
5
{% set items = {'apple': 'fruit', 'orange': 'fruit'} %}

{% set items = {'apple': 'unknown'}|merge(items) %}

{# items now contains {'apple': 'fruit', 'orange': 'fruit'} #}

Note

Internally, Twig uses the PHP array_merge function. It supports Traversable objects by transforming those to arrays.