blob: c5ceb7d050861a4bf750651f11291623dea58d86 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``reverse``
2===========
3
4The ``reverse`` filter reverses a sequence, a mapping, or a string:
5
6.. code-block:: twig
7
8 {% for user in users|reverse %}
9 ...
10 {% endfor %}
11
12 {{ '1234'|reverse }}
13
14 {# outputs 4321 #}
15
16.. tip::
17
18 For sequences and mappings, numeric keys are not preserved. To reverse
19 them as well, pass ``true`` as an argument to the ``reverse`` filter:
20
21 .. code-block:: twig
22
23 {% for key, value in {1: "a", 2: "b", 3: "c"}|reverse %}
24 {{ key }}: {{ value }}
25 {%- endfor %}
26
27 {# output: 0: c 1: b 2: a #}
28
29 {% for key, value in {1: "a", 2: "b", 3: "c"}|reverse(true) %}
30 {{ key }}: {{ value }}
31 {%- endfor %}
32
33 {# output: 3: c 2: b 1: a #}
34
35.. note::
36
37 It also works with objects implementing the `Traversable`_ interface.
38
39Arguments
40---------
41
42* ``preserve_keys``: Preserve keys when reversing a mapping or a sequence.
43
44.. _`Traversable`: https://secure.php.net/Traversable