1``merge``
2=========
3
4The ``merge`` filter merges an array with another array:
5
6.. code-block:: jinja
7
8    {% set values = [1, 2] %}
9
10    {% set values = values|merge(['apple', 'orange']) %}
11
12    {# values now contains [1, 2, 'apple', 'orange'] #}
13
14New values are added at the end of the existing ones.
15
16The ``merge`` filter also works on hashes:
17
18.. code-block:: jinja
19
20    {% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
21
22    {% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}
23
24    {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' } #}
25
26For hashes, the merging process occurs on the keys: if the key does not
27already exist, it is added but if the key already exists, its value is
28overridden.
29
30.. tip::
31
32    If you want to ensure that some values are defined in an array (by given
33    default values), reverse the two elements in the call:
34
35    .. code-block:: jinja
36
37        {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
38
39        {% set items = { 'apple': 'unknown' }|merge(items) %}
40
41        {# items now contains { 'apple': 'fruit', 'orange': 'fruit' } #}
42
43.. note::
44
45    Internally, Twig uses the PHP `array_merge`_ function. It supports
46    Traversable objects by transforming those to arrays.
47
48.. _`array_merge`: https://secure.php.net/array_merge
49