Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``merge`` |
| 2 | ========= |
| 3 | |
| 4 | The ``merge`` filter merges an array with another array: |
| 5 | |
| 6 | .. code-block:: twig |
| 7 | |
| 8 | {% set values = [1, 2] %} |
| 9 | |
| 10 | {% set values = values|merge(['apple', 'orange']) %} |
| 11 | |
| 12 | {# values now contains [1, 2, 'apple', 'orange'] #} |
| 13 | |
| 14 | New values are added at the end of the existing ones. |
| 15 | |
| 16 | The ``merge`` filter also works on hashes: |
| 17 | |
| 18 | .. code-block:: twig |
| 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 | |
| 26 | For hashes, the merging process occurs on the keys: if the key does not |
| 27 | already exist, it is added but if the key already exists, its value is |
| 28 | overridden. |
| 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:: twig |
| 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 |