ColdFusion Loops (cfloop)

A ColdFusion loop is a block of code that executes continuously either a specified number of times, once for each element in an object, or while a condition is true.

In ColdFusion, you use the <cfloop> tag to perform a loop. The <cfloop> tag has a number of different attributes. The attributes used depends on the type of loop you're performing.

Syntax

The Index Loop

An index loop is a loop that continues for a specified number of times.

You use the from and to attributes to specify how many iterations should occur. The index attribute holds the counter - it starts with the value of the to attribute and is incremented for each iteration of the loop (until it reaches the value of the from attribute).

ColdFusion code:

Display in browser:

1
2
3
4
5

The (optional) step attribute allows you to determine how big the increments will be.

ColdFusion code:

Display in browser:

1
3
5
7
9

The Conditional Loop

A conditional loop is a loop that executes while a condition is true.

You use the condition attribute to specify the condtion to use.

The following example uses a variable to determine whether to reiterate the loop or not. If the value of the variable is equal to false, the loop will continue to iterate. If it is set to true, it will exit the loop and continue the rest of the code.

In this example, we use ColdFusion's RandRange() function to pick a random number between 1 and 10. If the number is 10, the myVar variable is set to true.

ColdFusion code:

Display in browser:

Refresh this page a few times and you should see the number of lines change (due to a different random number being generated within the loop).

myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = true (loop has finished)

The Query Loop

You can loop over the results of a ColdFusion query (i.e. using the <cfquery> tag). Don't worry — if you don't know what I mean by that, we will be learning about ColdFusion queries soon.

ColdFusion code:

Display in browser:

Borat
Crocodile Dundee
Lord of the Rings
Last Samurai

The List Loop

You can loop over a list.

You can use the (optional) delimiter attribute to specify which characters are used as separators in the list.

Display in browser:

ColdFusion
HTML
XML

The File Loop

You can loop over a file. To do this, you use the same attributes as you would for a list.

COM Collection/Structure Loops

You can loop over a Structure or COM collection.

Display in browser:

XML: Inside XML
ColdFusion: ColdFusion MX Bible
HTML: HTML Visual QuickStart