Setting the step size on an indexed loop in ColdFusion using the CFLOOP tag

Readability

Setting the step size on an indexed loop in ColdFusion using the CFLOOP tag

In a pre­vi­ous exam­ple, “Cre­at­ing a sim­ple index loop in Cold­Fu­sion using the CFLOOP tag”, we saw how you could cre­ate a sim­ple index loop in Cold­Fu­sion using the <CFLOOP> tag and set­ting the index, from and to attributes.

The fol­low­ing exam­ple shows how you can set the step size on an indexed loop using the <CFLOOP> tag and spec­i­fy­ing the step attribute.

 
    counter == #counter#

The pre­ced­ing code pro­duces the fol­low­ing output:

counter == 1
counter == 11
counter == 21
counter == 31
counter == 41

If you want to loop back­wards, you can set a neg­a­tive step attribute, as seen in the fol­low­ing example:

 
    counter == #counter#

The pre­ced­ing code pro­duces the fol­low­ing output:

counter == 50
counter == 40
counter == 30
counter == 20
counter == 10

In a previous example, “Creating a simple index loop in ColdFusion using the CFLOOP tag”, we saw how you could create a simple index loop in ColdFusion using the <CFLOOP> tag and setting the index, from and to attributes.

The following example shows how you can set the step size on an indexed loop using the <CFLOOP> tag and specifying the step attribute.

<cfloop index="counter" from="1" to="50" step="10"> 
    <cfoutput>counter == #counter#<br/></cfoutput> 
</cfloop>

The preceding code produces the following output:

counter == 1
counter == 11
counter == 21
counter == 31
counter == 41

If you want to loop backwards, you can set a negative step attribute, as seen in the following example:

<cfloop index="counter" from="50" to="1" step="-10"> 
    <cfoutput>counter == #counter#<br/></cfoutput> 
</cfloop>

The preceding code produces the following output:

counter == 50
counter == 40
counter == 30
counter == 20
counter == 10

Leave a Reply

Your email address will not be published.