There are several different types of loops in ColdFusion and sometimes it can be difficult to know which one to use and what properties are required to use it. This post is designed as a resource in deciding on the best loop for the job and how to write that particular loop. Also included is a quick reference PDF to print out that will help you remember which ones to use.
At the top of our list is the list loop. The list loop is used when looping over any data that can be broken apart as a list. Remember in ColdFusion you can use different delimiters for lists, so you aren’t limited to just commas. For our example, lets consider a non-normal list such as a URL like so: http://domain.com/blog/my-first-post/comments. I’ve actually had to parse over a URL like this before. Looking at this string we can break apart the list by each forward slash. For our example, I don’t want the “http” so I’ll remove it as well.
The file loop is exactly like the list loop, except the list isn’t a string you give it but a file that can be read by ColdFusion. Using the same syntax above but changing the delimiter to the new linefeed and carriage return, we can output over each line of the file.
The index loop is the simplest of the loops. It simply loops from point a to point b that you specify. It’s not that smart but it can get the job done when need be. For our example, we’ll pretend we want to loop based on the size of an array. In an index loop, there is a special character called an index that holds the value of the loop we are one. The index starts at the value you enter for start and counts up until it reaches the value of to.
The conditional loop is one of the few loops with real logic. The conditional loop will continue to run until the condition it is checking returns false. Once it does, it moves on. If you setup your conditional loop incorrectly it could crash your program as it will possibly run forever. In our example we’ll run our loop until we find strawberries.
The query loop is probably the most used as typically when grabbing data from a database, you need to output it. The query loop is designed to loop over data until all rows have been looped.
The collection/structure loop is very similar to the query loop in that is loops over the keys in a structure in the same way a query loop runs over the rows in a query. With the collection loop however, the item holds only the key of the structure. One draw back to the collection/structure loop is that structs aren’t in a particular order like queries.
Download the quick reference guide to see limited syntax of these loop types for quick reference.