# CFLOOP

Looping is a very powerful programming technique that lets you repeat a set of instructions or display output over and over until one or more conditions are met. CFLOOP supports five different types of loops:

- Index Loops
- Conditional Loops
- Looping over a Query
- Looping over a List
- Looping over a COM Collection or Structure

The type of loop is determined by the attributes of the CFLOOP tag.

## Index Loops

An index loop repeats for a number of times determined by a range of numeric values. Index loops are commonly known as FOR loops, as in "loop FOR this range of values. "

### Syntax

    <CFLOOP INDEX="parameter_name"
        FROM="beginning_value"
        TO="ending_value"
        STEP="increment">
        ...
        HTML or CFML code to execute
         ...
    </CFLOOP>

#### INDEX

Required. Defines the parameter that is the index value. The index value will be set to the FROM value and then incremented by 1 (or the STEP value) until it equals the TO value.

#### FROM

Required. The beginning value of the index.

#### TO

Required. The ending value of the index.

#### STEP

Optional. Default is 1. Sets the value by which the loop INDEX value is incremented each time the loop is processed.

### Examples

In this example, the INDEX variable is incremented for each iteration of the loop. The following code loops five times, displaying the INDEX value of the loop each time:

    <CFLOOP INDEX="LoopCount"
        FROM="1" TO="5">
    The loop index is <CFOUTPUT>#LoopCount#</CFOUTPUT>.<BR>

    </CFLOOP>

The result of this loop in a browser looks like this:

    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.

In this example, the STEP value has a default value of 1. But you can set the STEP value to change the way the INDEX value is incremented. The following code counts backwards from 5:

    <CFLOOP INDEX="LoopCount"
        FROM="5"
        TO="1"
        STEP="-1">
    The loop index is <CFOUTPUT>#LoopCount#</CFOUTPUT>.<BR>

    </CFLOOP>

The result of this loop in a browser looks like this:

    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.

## Conditional Loops

A conditional loop iterates over a set of instructions while a given condition is TRUE. To use this type of loop correctly, the instructions must change the condition every time the loop iterates until the condition evaluates as FALSE. Conditional loops are commonly known as WHILE loops, as in "loop WHILE this condition is true. "

### Syntax

    <CFLOOP CONDITION="expression">

#### CONDITION

Required. Sets the condition that controls the loop. The loop will repeat as long as the condition evaluates as TRUE. When the condition is FALSE, the loop stops.

### Example

The following example increments the parameter "CountVar " from 1 to 5. The results look exactly like the Index loop example.

    <!--- Set the variable CountVar to 0 --->
    <CFSET CountVar=0>

    <!--- Loop until CountVar = 5 --->
    <CFLOOP CONDITION="CountVar LESS THAN OR EQUAL TO 5">

        <CFSET CountVar=CountVar + 1>
        The loop index is <CFOUTPUT>#CountVar#</CFOUTPUT>.<BR>

    </CFLOOP>

The result of this loop in a browser would look something like:

    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.

## Looping over a Query

A loop over a query repeats for every record in the query record set. The CFLOOP results are just like a CFOUTPUT. During each iteration of the loop, the columns of the current row will be available for output. CFLOOP allows you to loop over tags that can not be used inside CFOUTPUT.

### Syntax

    <CFLOOP QUERY="query_name"
        STARTROW="row_num"
        ENDROW="row_num">

#### QUERY

Required. Specifies the query that will control the loop.

#### STARTROW

Optional. Specifies the first row of the query that will be included in the loop.

#### ENDROW

Optional. Specifies the last row of the query that will be included in the loop.

### Example 1

The following example shows a CFLOOP looping over a query that works in the same way as a CFOUTPUT tag using the QUERY attribute:

    <CFQUERY NAME="MessageRecords"
        DATASOURCE="cfsnippets">
        SELECT * FROM Messages
    </CFQUERY>

    <CFLOOP QUERY="MessageRecords">
        <CFOUTPUT>#Message_ID#</CFOUTPUT><BR>
    </CFLOOP>

### Example 2

CFLOOP also provides iteration over a recordset with dynamic starting and stopping points. Thus you can begin at the tenth row in a query and end at the twentieth. This mechanism provides a simple means to get the next n sets of records from a query.

The following example loops from the tenth through the twentieth record returned by "MyQuery ":

    <CFSET Start=10>
    <CFSET End=20>

    <CFLOOP QUERY="MyQuery"
        STARTROW="#Start#"
        ENDROW="#End#">

        <CFOUTPUT>#MyQuery.MyColName#</CFOUTPUT><BR>

    </CFLOOP>

The loop is done when there are no more records or when the current record is greater than the value of the ENDROW attribute.

### Example 3

The advantage of looping over a query is that you can use CFML tags that are not allowed in a CFOUTPUT. The following example combines the pages returned by a query of a list of page names into a single document using the CFINCLUDE tag.

    <CFQUERY NAME="GetTemplate"
        DATASOURCE="Library"
        MAXROWS="5">
        SELECT TemplateName FROM Templates
    </CFQUERY>

    <CFLOOP QUERY="TemplateName">
        <CFINCLUDE TEMPLATE="#TemplateName#">
    </CFLOOP>

## Looping over a List

Looping over a list offers the option of walking through elements contained within a variable or value returned from an expression. In a list loop, the INDEX attribute specifies the name of a variable to receive the next element of the list, and the LIST attribute holds a list or a variable containing a list.

### Syntax

    <CFLOOP INDEX="index_name"
        LIST="list_items"
        DELIMITERS="item_delimiter">
    </CFLOOP>

#### INDEX

Required. In a list loop, the INDEX attribute specifies the name of a variable to receive the next element of the list, and the LIST attribute holds a list or a variable containing a list.

#### LIST

Required. The list items in the loop, provided directly or with a variable.

#### DELIMITERS

Optional. Specifies the delimiter characters used to separate items in the LIST.

### Example

This loop will display the names of each of the Beatles:

    <CFLOOP INDEX="ListElement"
        LIST="John,Paul,George,Ringo">
            <CFOUTPUT>#ListElement#</CFOUTPUT><BR>
    </CFLOOP>

Although CFLOOP expects elements in the list to be separated by commas by default, you are free to specify your own element boundaries in the DELIMITER attribute. Here's the same loop as before, only this time CFLOOP will treat commas, colons, or slashes as list element delimiters:

    <CFLOOP INDEX="ListElement"
        LIST="John/Paul,George::Ringo"
        DELIMITERS=",:/">
            <CFOUTPUT>#ListElement#</CFOUTPUT><BR>
    </CFLOOP>

Delimiters need not be specified in any particular order. Note that consecutive delimiters are treated as a single delimiter; thus the two colons in the previous example are treated as a single delimiter between "George " and "Ringo. "

## Looping over a COM Collection or Structure

The CFLOOP COLLECTION attribute allows you to loop over a structure or a COM/DCOM collection object:

- A COM/DCOM collection object is a set of similar items referenced as a group rather than individually. For example, the group of open documents in an application is a type of collection.
- A structure can contain either a related set of items or be used as an associative array. Looping is particularly useful when using a structure as an associative array.

Each collection item is referenced in the CFLOOP by the variable name that you supply in the ITEM attribute. This type of an iteration is generally used to access every object within a COM/DCOM collection or every element in the structure. The loop is executed until all objects have been accessed.

The COLLECTION attribute is used with the ITEM attribute in a CFLOOP. In the example that follows, ITEM is assigned a variable called`file2, so that with each cycle in the CFLOOP, each item in the collection is referenced. In the CFOUTPUT section, the name property of the file2 item is referenced for display.`

### Examples

This example employs a COM object to output a list of files. In this example, `FFUNC` is a collection of `file2` objects.

    <CFOBJECT CLASS=FileFunctions.files
        NAME=FFunc
        ACTION=Create>

    <CFSET FFunc.Path = "c:\">
    <CFSET FFunc.Mask = "*.*" >
    <CFSET FFunc.attributes = 16 >
    <CFSET x=FFunc.GetFileList()>

    <CFLOOP COLLECTION=#FFUNC# ITEM=file2>
        <CFOUTPUT>
            #file2.name# <BR>
        </CFOUTPUT>
    </CFLOOP>

This example loops through a structure (used as an associative array):

    ...<!--- Create a structure and loop through its contents --->
    <CFSET Departments=StructNew()>
    <CFSET val=StructInsert(Departments, "John ", "Sales ")>
    <CFSET val=StructInsert(Departments, "Tom ", "Finance ")>
    <CFSET val=StructInsert(Departments, "Mike ", "Education ")>

    <!--- Build a table to display the contents --->

    <CFOUTPUT>
    <TABLE cellpadding= "2 " cellspacing= "2 ">
        <TR>
        <TD><B>Employee</B></TD>
        <TD><B>Dept.</B></TD>
        </TR>

    <!--- In CFLOOP, use ITEM to create a variable
        called person to hold value of key as loop runs --->
    <CFLOOP COLLECTION=#Departments# ITEM= "person ">
        <TR>
        <TD>#person#</TD>
        <TD>#StructFind(Departments, person)#</TD>
        </TR>
    </CFLOOP>
    </TABLE>
    </CFOUTPUT>
    ...