Mar 24, 2008

Looping backwards over a list or array

Many months back I was on a job interview and someone asked me to loop backwards over a name, essentially spelling it backwards. What an odd request. I fumbled around and was totally stumped. I didn't get the job, but you can bet your ass I figured out how to loop backwards over a list/array or whatever. Below is the proof of concept example code.

Enjoy.

<!---Loop backwards example.--->

<!---First we are going to create a list.--->

<cfset myList = "F,r,a,n,k,T,u,d,o,r">

<!---Next we are going to create an array out of it.--->

<cfset myArray = listToArray(myList)>

<!---Now weare going to set up our loop with parameters.--->

<br>

<!---Note that I am setting the from and to max to min and

setting step to -1 so it can step backwards throught he loop.

--->

<cfoutput>

<cfloop from="#arrayLen(myArray)#" to="1" step="-1" index="i" >

#myArray[i]#<br>

</cfloop>

</cfoutput>

Labels: , , , ,