Is there an easy way to list from a to z in the alphabet?
There are few ways to loop over the letters A to Z using ColdFusion. Some are more complicated than others, but perhaps more useful. Let's start off by looking at traditional list loop. If you want, you could create a list of all letters between A and Z and loop over that:
<!--- Loop over letters as a list. ---> <cfloop index="strLetter" list="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" delimiters=","> #strLetter# </cfloop>
This method is VERY simple and VERY straightforward. But, on the other hand, it is prone to error. Are you sure you wrote down all the letters? Did you miss any?
The next method would be to use an index loop based on the ASCII values of the letters from A to Z. The ASCII values are such that going from A to Z is an incrementing value list.
<!--- Loop over ascii values. ---> <cfloop index="intLetter" from="#Asc( 'A' )#" to="#Asc( 'Z' )#" step="1"> <!--- Get character of the given ascii value. ---> <cfset strLetter = Chr( intLetter ) /> #strLetter# </cfloop>
This reduces room for error since you don't have to write out all of the letters. But on the flip side, you have go through the extra step of converting the ASCII value back to a character value, and it might not be as straight forward to someone reading the code.
Sometimes, what I like to do is load the letters right into a query. I find a query loop more intuitive some reason and it is much more reusable than a standard list.
<!--- Create a query for the letters. ---> <cfset qLetter = QueryNew( "" ) /> <!--- Add the letters (one per record) to the query. ---> <cfset QueryAddColumn( qLetter, "name", "CF_SQL_VARCHAR", ListToArray( "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" ) ) /> <!--- Loop over letter query. ---> <cfloop query="qLetter"> #qLetter.name# </cfloop>
This is clearly the most complicated of the three options, and certainly the least straight forward... but, I once you get the letters into the query, they are highly reusable. The physical CFLoop tag is much more simple, and it's more intuitive to scope the letter (which will reduce naming conflicts).
In practice, I tend to go with the ASC() to ASC() value index loop. It is a good combination of clear-to-read code and reduced risk of error.
Want to use code from this post? Check out the license.