blob: 3dc5f4d73b7b3c9cd5d559da173093102a824ffa [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``sort``
2========
3
4The ``sort`` filter sorts an array:
5
6.. code-block:: twig
7
8 {% for user in users|sort %}
9 ...
10 {% endfor %}
11
12.. note::
13
14 Internally, Twig uses the PHP `asort`_ function to maintain index
15 association. It supports Traversable objects by transforming
16 those to arrays.
17
18You can pass an arrow function to sort the array:
19
20.. code-block:: html+twig
21
22 {% set fruits = [
23 { name: 'Apples', quantity: 5 },
24 { name: 'Oranges', quantity: 2 },
25 { name: 'Grapes', quantity: 4 },
26 ] %}
27
28 {% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
29 {{ fruit }}
30 {% endfor %}
31
32 {# output in this order: Oranges, Grapes, Apples #}
33
34Note the usage of the `spaceship`_ operator to simplify the comparison.
35
36Arguments
37---------
38
39* ``arrow``: An arrow function
40
41.. _`asort`: https://secure.php.net/asort
42.. _`spaceship`: https://www.php.net/manual/en/language.operators.comparison.php