December 19, 2018
Quick Tip: Negative Indexing on arrays in ColdFusion 2018
Comments
(0)
December 19, 2018
Quick Tip: Negative Indexing on arrays in ColdFusion 2018
Wizard 28 posts
Followers: 14 people
(0)

Imagine the following array of letters in the English alphabet:

<cfset variables.Alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']>

Why are you creating an array of letters in the English alphabet?  Who knows… and who cares.  It’s a quick tip so try not to get wrapped up in the why of things.

Now imagine that you needed to display the first, tenth, and last elements in that array in an unordered list.  In the past, I would have done it like so:

<cfoutput>
<ul>
     <li>#variables.Alphabet[1]#</li>
     <li>#variables.Alphabet[10]#</li>
     <li>#variables.Alphabet[arrayLen(variables.Alphabet)]#</li>
</ul>
</cfoutput>

But with negative indexing in ColdFusion 2018, I can address the array from the back by simply applying a negative index.

<cfoutput>
<ul>
     <li>#variables.Alphabet[1]#</li>
     <li>#variables.Alphabet[10]#</li>
     <li>#variables.Alphabet[-1]#</li>
</ul>
</cfoutput>

Using -1 as the index of the array will pull from the end of the array and display the last element.  (“Z” in our case.)  An index of -2 would display “Y”, and so on and so forth.

Happy coding!

0 Comments
Add Comment