HEX
Server: Apache
System: Linux v38079.2is.nl 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64
User: democfellows (10015)
PHP: 8.1.34
Disabled: opcache_get_status
Upload Files
File: /var/www/vhosts/creativefellows.nl/recht.creativefellows.nl/vendor/twig/twig/doc/filters/sort.rst
``sort``
========

The ``sort`` filter sorts an array:

.. code-block:: twig

    {% for user in users|sort %}
        ...
    {% endfor %}

.. note::

    Internally, Twig uses the PHP `asort`_ function to maintain index
    association. It supports Traversable objects by transforming
    those to arrays.

You can pass an arrow function to sort the array:

.. code-block:: html+twig

    {% set fruits = [
        { name: 'Apples', quantity: 5 },
        { name: 'Oranges', quantity: 2 },
        { name: 'Grapes', quantity: 4 },
    ] %}

    {% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
        {{ fruit }}
    {% endfor %}

    {# output in this order: Oranges, Grapes, Apples #}

Note the usage of the `spaceship`_ operator to simplify the comparison.

Arguments
---------

* ``arrow``: An arrow function

.. _`asort`: https://www.php.net/asort
.. _`spaceship`: https://www.php.net/manual/en/language.operators.comparison.php