An index loop repeats for a number of times determined by a range of numeric values. Index loops are known as FOR loops, as in "loop FOR this range of values. "
<cfloop index = "parameter_name" from = "beginning_value" to = "ending_value" step = "increment"> ... HTML or CFML code to execute ... </cfloop>
cfabort,
cfbreak,
cfexecute,
cfexit,
cfif cfelseif cfelse,
cflocation,
cfrethrow,
cfswitch cfcase cfdefaultcase,
cfthrow,
cftry cfcatch
When coding an index loop, using anything other than integer values for in the from
and to
attributes can product unexpected results. For example, if you increment through an index loop between 1 and 2 with a step of 0.1, ColdFusion outputs "1,1.1,1.2,...,1.9", but NOT "2". This is a well known problem in programming languages that has to do with the internal representation of floating point numbers.
Note The |
In this example, the index
variable is incremented for each iteration of the loop. The following code loops five times, displaying the index
value of the loop each time:
<cfloop index = "LoopCount" from = "1" to = "5">
The loop index is <cfoutput>#LoopCount#</cfoutput>.<br> </cfloop>
The result of this loop in a browser looks like this:
The loop index is 1. The loop index is 2. The loop index is 3. The loop index is 4. The loop index is 5.
In this example, the index
variable is incremented for each iteration of the loop. The following code loops four times, displaying the index
value of the loop each time. The value of j is decreased by one for each iteration of the loop, but that does not affect the to
value because it is a copy of j before entering the loop.
<cfset j = 4>
<cfloop index = "LoopCount" from = "1" to = #j#> <cfoutput>The loop index is #LoopCount#</cfoutput>.<br> <cfset j = j - 1> </cfloop>
The result of this loop in a browser looks like this:
The loop index is 1. The loop index is 2. The loop index is 3. The loop index is 4.
In this example, the step
value has the default value of 1. But you can set the step
value to change the way the index
value is incremented. The following code decrements the index by 1 from 5:
<cfloop index = "LoopCount"
from = "5" to = "1" step = "-1"> The loop index is <cfoutput>#LoopCount#</cfoutput>.<br> </cfloop>
The result of this loop in a browser looks like this:
The loop index is 5. The loop index is 4. The loop index is 3. The loop index is 2. The loop index is 1.