1

Let's say we have this setup:

{% set myArray = [9,3,5,7,2,1] %}
{% set mySortedArray = myArray | supersort() %}

It gives us:

myArray = array(6) {
    [0]=int(9)
    [1]=int(3)
    [2]=int(5)
    [3]=int(7)
    [4]=int(2)
    [5]=int(1)
}

mySortedArray = array(6) {
    [5]=int(1)
    [4]=int(2)
    [1]=int(3)
    [2]=int(5)
    [3]=int(7)
    [0]=int(9)
}

How can I access say the second element of mySortedArray?

If I do {{ mySortedArray[2] }} I get 5, but I want the 3.

1

If you run mySortedArray through the | values filter, it will reset the keys:

{% set mySortedArray = myArray | supersort | values %}
mySortedArray = array(6) {
    [0]=int(1)
    [1]=int(2)
    [2]=int(3)
    [3]=int(5)
    [4]=int(7)
    [5]=int(9)
}
1
  • Gee, I had scrutinised all the Twig filters but forgotten about Craft's! Thank you for the reminder. – Crafty Cat Sep 4 '20 at 5:51
1

Further to Jalen's answer, if you want to preserve your array keys, you can use this:

{% set sortedArrayKeys = mySortedArray | keys %}

and then access any item with

mySortedArray[sortedArrayKeys[index]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.