<cfloop>
Looping is a very powerful programming technique that lets you repeat a set of instructions or display output repeatedly until one or more conditions are met.
cfloop supports five types of loops.
This tag must have a body.
This tag is also supported within <cfscript>
<cfloop
index=string
from=number
to=number
step=number
condition=string
query=object
startrow=number
endrow=number
maxrows=number
list=string
array=array
delimiters=string
collection=any
struct=struct
item=string
file=string
characters=number
startline=number
endline=number
charset=string
group=string
groupcasesensitive=boolean
label=string
times=numeric
><!--- body ---></cfloop>
Examples
Index & Conditional loop
<cfloop index = "LoopCount" from = "1" to = "5">
The loop index is <cfoutput>#LoopCount#</cfoutput><br>
</cfloop>
<br><u>Conditional loop</u><br>
<cfset CountVar = 1>
<cfloop condition = "CountVar LESS THAN OR EQUAL TO 5">
<cfset CountVar = CountVar + 1>
CountVar is <cfoutput>#CountVar#</cfoutput><br>
</cfloop>
List loop
<cfset listEle = "lucee,test,case">
<br><u>Simple list loop</u><br>
<cfloop list="#listEle#" index="res">
<cfoutput>#res#</cfoutput><br>
</cfloop>
<br><u>List loop</u><br>
<cfset listDeliEle = "I;Love;Lucee">
<cfloop list="#listDeliEle#" index="element" delimiters=";">
<cfoutput>#element#</cfoutput><br>
</cfloop>
<br><u>deli loop with index</u><br>
<cfloop index="a" from="1" to="#listlen(listEle)#">
<cfoutput>#listgetat(listEle,a)#</cfoutput><br>
</cfloop>
<br><u>Condition with list</u><br>
<cfset cV = 1>
<cfloop condition="cv lte #listlen(listele)#">
<cfoutput>#listgetat(listEle,cV)#</cfoutput><br>
<cfset cV = cV+1>
</cfloop>
Array loop & Struct loop
<cfoutput>
<cfset arr = ["I","Love","Lucee"]>
<br><u>Array using index loop</u><br>
<cfloop array="#arr#" index="arr">
#arr#<br>
</cfloop>
<cfset Departments = {"Save ":"Water ", "Plant ":"gren ", "Protect ":"Earth "}>
<br><u>Struct loop</u><br>
<cfloop collection="#Departments#" item = "person">
#person#
#StructFind(Departments, person)#<br>
</cfloop>
</cfoutput>
Query loop
<cfset qry = ExtensionList()>
<cfloop query="#qry#">
<cfoutput>#qry.currentrow#</cfoutput>
</cfloop>
<br>
<cfscript>
loop query="#qry#"{
echo( qry.currentrow & " " );
if (qry.currentrow eq 10)
break;
if (qry.currentrow mod 2 eq 1)
continue;
echo( "... " );
}
</cfscript>
See also
- Core CFML Language
- Loop - times
- <cfbreak>
- <cfcontinue>
- <cfwhile>
- Search Issue Tracker
- Search Lucee Test Cases (good for further, detailed examples)