ksort Twig Filter
The ksort filter sorts a hash or an array by its keys. By default, it will sort in ascending order (A-Z), but you can pass the direction argument to have it sort in descending order (Z-A).
You would typically save the sorted array back to the original variable or to a new variable.
{% set array = array|ksort %}
{% set hash = hash|ksort('desc') %}
Instead of passing the direction argument you could simply use the krsort filter to sort in descending order.
You can use this filter within a for loop.
{% for item in items|ksort %}
...
{% endfor %}
You can also use this filter in combination with the join filter to sort and output the array values in one step.
{{ [5,8,2,3]|ksort|join(', ') }}
That would output: 2, 3, 5, 8
Arguments
The ksort filter has the following signature.
ksort(direction)
Argument | Description |
---|---|
direction |
Sets the direction to sort by. Allowed values are: "asc" or "desc". "asc" means that the sorting will be in ascending order (A-Z). "desc" means that the sorting will be in descending order (Z-A). If this parameter is not passed then sorting will be done in ascending order. Example {% set array = array|ksort('desc') %} |