Description
An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.
Syntax
index = "parameter name" from = "beginning value" to = "ending value" step = "increment" charset "charset to read in a file"> HTML or CFML code ... </cfloop>
See also
cfabort, cfbreak, cfcontinue, cfdirectory, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfswitch, cfthrow, cftry; cfloop and
cfbreak in the Developing ColdFusion Applications
Attributes
Attribute |
Req/Opt |
Default |
Description |
---|---|---|---|
index |
Required |
|
Index value. ColdFusion sets it to the from value and increments or decrements by step value, until it equals the to value. |
from |
Required |
|
Beginning value of index. |
to |
Required |
|
Ending value of index. |
step |
Optional |
1 |
Step by which to increment or decrement the index value. |
charset |
optional |
|
Charset to use when reading in a file line-by-line. |
Usage
Using anything other than integer values in the from and to attributes of an index loop can product unexpected results. For example, if you increment through an index loop from 1 to 2, with a step of 0.1, ColdFusion outputs "1,1.1,1.2,...,1.9", but not "2". This is a programming language problem regarding the internal representation of floating point numbers.
The to value is evaluated once, when the cfloop tag is encountered. Any change to this value within the loop block, or within the expression that evaluates to this value, does not affect the number of times the loop is executed.
Example
<cfloop index="i" from="1" to="5" > The loop index is <cfoutput>#i#</cfoutput>.<br> </cfloop>
The output of this loop is as follows:
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.
<cfset j=5/> <cfloop index = "LoopCount" from = "1" to = #j#> <cfoutput>The loop index is #LoopCount#</cfoutput>.<br/> <cfset j = j - 1> </cfloop>
The output of this loop is as follows:
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.
<cfloop index = "LoopCount" from = "5" to = "1" step = "-1"> The loop index is <cfoutput>#LoopCount#</cfoutput>.<br/> </cfloop>
The output of this loop is as follows:
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.