Creating a simple conditional loop in ColdFusion using the CFLOOP tag

Readability

Creating a simple conditional loop in ColdFusion using the CFLOOP tag

In pre­vi­ous exam­ples, “Cre­at­ing a sim­ple index loop in Cold­Fu­sion using the CFLOOP tag” and “Set­ting the step size on an indexed 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 using the index, from, and to, and step attributes.

The fol­low­ing exam­ple shows how you can cre­ate a sim­ple con­di­tional loop in Cold­Fu­sion using the <CFLOOP> tag using the condition 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

The pre­vi­ous exam­ple used a con­di­tion of LESS THAN, it is impor­tant to note that you can instead use the short­hand nota­tion of LT. You could also use a con­di­tion of LESS THAN OR EQUAL TO (or use the LTE short­hand), or GREATER THAN (or GT short­hand), or GREATER THAN OR EQUAL TO (or GTE shorthand).



    counter == #counter#


    counter == #counter#


    counter == #counter#

In previous examples, “Creating a simple index loop in ColdFusion using the CFLOOP tag” and “Setting the step size on an indexed loop in ColdFusion using the CFLOOP tag”, we saw how you could create a simple index loop in ColdFusion using the <CFLOOP> tag using the index, from, and to, and step attributes.

The following example shows how you can create a simple conditional loop in ColdFusion using the <CFLOOP> tag using the condition attribute.

<cfset counter = 1>
<cfloop condition="counter LESS THAN 50">
    <cfoutput>counter == #counter#<br/></cfoutput>
    <cfset counter = counter + 10 />
</cfloop>

The preceding code produces the following output:

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

The previous example used a condition of LESS THAN, it is important to note that you can instead use the shorthand notation of LT. You could also use a condition of LESS THAN OR EQUAL TO (or use the LTE shorthand), or GREATER THAN (or GT shorthand), or GREATER THAN OR EQUAL TO (or GTE shorthand).

<cfset counter = 1>
<cfloop condition="counter LTE 51">
    <cfoutput>counter == #counter#<br/></cfoutput>
    <cfset counter = counter + 10 />
</cfloop>
<cfset counter = 1>
<cfloop condition="counter LESS THAN OR EQUAL TO 51">
    <cfoutput>counter == #counter#<br/></cfoutput>
    <cfset counter = counter + 10 />
</cfloop>
<cfset counter = 51>
<cfloop condition="counter GREATER THAN OR EQUAL TO 1">
    <cfoutput>counter == #counter#<br/></cfoutput>
    <cfset counter = counter - 10 />
</cfloop>

Leave a Reply

Your email address will not be published.