Attribute | Required | Type | Default | Description |
---|---|---|---|---|
index | true | string | Variable name for the loop's index. Defaults to the variables scope. | |
from | true | numeric | Starting value for the index. | |
to | true | numeric | Ending value for the index. | |
step | false | numeric | 1 | Value by which to increase or decrease the index per iteration. |
Final value of
x
is 10.
<!--- Tags --->
<cfoutput>
<cfloop index="x" from="1" to="10">
<li>#x#</li>
</cfloop>
</cfoutput>
<!--- cfscript --->
<cfscript>
for (x = 1; x <= 10; x++) {
writeOutput('<li>' & x & '</li>');
}
</cfscript>
<!--- HTML Output --->
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Final value of
x
is 11.
<!--- Tags --->
<cfoutput>
<cfloop index="x" from="1" to="10" step="2">
<li>#x#</li>
</cfloop>
</cfoutput>
<!--- cfscript --->
<cfscript>
for (x = 1; x <= 10; x += 2) {
writeOutput('<li>' & x & '</li>');
}
</cfscript>
<!--- HTML Output --->
- 1
- 3
- 5
- 7
- 9
Final value of
x
is 0.
<!--- Tags --->
<cfoutput>
<cfloop index="x" from="10" to="1" step="-1">
<li>#x#</li>
</cfloop>
</cfoutput>
<!--- cfscript --->
<cfscript>
for (x = 10; x > 0; x--) {
writeOutput('<li>' & x & '</li>');
}
</cfscript>
<!--- HTML Output --->
- 10
- 9
- 8
- 7
- 6
- 5
- 4
- 3
- 2
- 1
Make sure to
var
orlocal
scope the index inside a function.Foo()
returns 11.
<!--- var scope --->
<cffunction name="foo" access="public" output="false" returntype="numeric">
<cfset var x = 0 />
<cfloop index="x" from="1" to="10" step="1">
<cfset x++ />
</cfloop>
<cfreturn x />
</cffunction>
<!--- Local scope --->
<cffunction name="foo" access="public" output="false" returntype="numeric">
<cfloop index="local.x" from="1" to="10" step="1">
<cfset local.x++ />
</cfloop>
<cfreturn local.x />
</cffunction>
The cfscript function
cfloop
has no support forindex
as a stand alone counter mechanism.