coldfusion CFLOOP How-To Index

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Parameters

AttributeRequiredTypeDefaultDescription
indextruestringVariable name for the loop's index. Defaults to the variables scope.
fromtruenumericStarting value for the index.
totruenumericEnding value for the index.
stepfalsenumeric1Value by which to increase or decrease the index per iteration.

Basic index loop

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

Increase step to 2

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

Decrement step by 1

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

CFLoop in a Function

Make sure to var or local 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>

ColdFusion 11 through current

The cfscript function cfloop has no support for index as a stand alone counter mechanism.



Got any coldfusion Question?