Sort ViewHelper <f:sort> 

The SortViewHelper sorts the items of an array in ascending or descending order. Items with equal values keep their original order.

Items are sorted in human order: numbers and numeric strings are compared by their value, so 11 comes before 100. Other strings are compared in natural, case-insensitive order, so 'img2.png' comes before 'img10.png', like PHP's strnatcasecmp() function. All other values, for example dates, are compared with PHP's comparison rules.

If a property is given, the items are sorted by the value of that property instead. The items can then be arrays or objects. Properties are accessed the same way as variables in templates, so getter methods and nested property paths like author.name are supported.

Iterators like generators can yield the same key more than once. All of their items are used, unless preserveKeys is set: then only the last item per key is used, like with PHP's iterator_to_array() function.

Examples 

Sort an array 

Given numbers = [100, 9, 11]:

<f:sort value="{numbers}" />
Copied!
[9, 11, 100]
Copied!

Sort strings in human order 

Given files = ['img12.png', 'IMG10.png', 'img2.png', 'img1.png']:

<f:sort value="{files}" />
Copied!
['img1.png', 'img2.png', 'IMG10.png', 'img12.png']
Copied!

Sort in descending order 

<f:sort value="{numbers}" descending="true" />
Copied!
[100, 11, 9]
Copied!

Sort by a property 

Given products = [['title' => 'Book', 'price' => 12], ['title' => 'Pen', 'price' => 2.5]]:

<f:for each="{products -> f:sort(property: 'price')}" as="product">
    {product.title}
</f:for>
Copied!
Pen Book
Copied!

Go to the source code of this ViewHelper: SortViewHelper.php (GitHub).

Arguments

The following arguments are available for the sort ViewHelper:

descending

descending
Type
boolean
Default
false
If true, the items are sorted in descending order

preserveKeys

preserveKeys
Type
boolean
Default
false
If true, the keys of the original array are preserved. Otherwise the result is reindexed numerically.

property

property
Type
string
Name or path of the property to sort by, e.g. "title" or "author.name". If omitted, the items themselves are compared.

value

value
Type
array
The array to sort