by Michael Dinowitz
Of the five CFLOOP types, three create their own index variable. The question is, what is the value of this variable when the loop finishes running? The answer depends on the loop being used.
An index loop is the ColdFusion variant of the standard For loop. It takes a start value (from), an end value (to) and keeps track of the value in an index (index). The way this loop works is to compile all the steps at once, do the loop and if the loop index is ever greater than the "to" value, exit the loop. This means that the index value of a FOR type loop will be one iteration more than the "to" value. In the case below, the loop will exit with document_id having a value of 11.
<CFLOOP from="1" to="10" index="document_id"> <CFOUTPUT>#document_id#</CFOUTPUT> </CFLOOP> <CFOUTPUT>|#document_id#|</CFOUTPUT> |
A list loop will take some list and loop over each item in it. The current value (i.e. list item) will be stored in an index for use. In the example below, the first iteration will create a variable called document_id with a value of 1 (the first item in the list). The next iteration will reload the variable with a value of 2 (the second item in the list). When this loop exits, the document_id is set to NULL (i.e. a blank string). This means that a check against it with IsDefined() will return true but a check with len() will return 0.
<CFLOOP list="1,2" index="document_id"> <CFOUTPUT>#document_id#</CFOUTPUT> </CFLOOP> <CFOUTPUT>|#document_id#|</CFOUTPUT> |
A collection in ColdFusion terms is either a ColdFusion structure or a collection of data returned from a COM object. This loop type will take each item in the collection and load it into an index. In this loop, the index attribute is called item, but the result is the same; a variable is being created. When this loop exits, the item (index) will retain the last value that it was loaded with. For example, if the last item in a structure was HTTP_Referer than the value of the item outside the loop will be HTTP_Referer.
<CFLOOP collection="#Session#" item="document_id"> <CFOUTPUT>#document_id# - #session[document_id]#</CFOUTPUT> </CFLOOP> <CFOUTPUT>|#document_id#|</CFOUTPUT> |
This information may seem like trivia, but the index value of a loop can be a ColdFusion syntax error waiting to happen. If you name a loop index the same name as a variable being used later, you may get results you're not expecting. Such a case happened to me recently and it took me a little time to find the cause. This article is meant to save people that little time.
Michael Dinowitz has dedicated the last seven years of his life to the ColdFusion community and it doesn't look like he's stopping any time soon. His accomplishments include hosting the high volume CF-Talk list (as well as others) out of House of Fusion (www.houseoffusion.com) and publishing the Fusion Authority Weekly News Alert (www.fusionauthority.com/alert), as well as many other presentations and publications.