Skip to Content

How to Use CFBreak to Break A Loop in CFML

In this tutorial, you'll learn how to break out of a cfloop, cfwhile loop, or cfforeach loop in CFML by using the cfbreak tag.

Code Example

As an example, let's create a loop from index 1 to 10. Once the index value is greater than or equal to 5, the cfbreak tag will be executed and break out of the loop, halting further output:

<cfloop index="i" from="1" to="10">
<cfoutput>#i#</cfoutput>

<cfif i gte 5>
<cfbreak>
</cfif>
</cfloop>

The resulting output will be:

1 2 3 4 5

Script Syntax

Here is the script syntax version to achieve the same output:

<cfscript>
for (i = 1; i <= 10; i++) {
writeOutput(i);

if (i >= 5) {
break;
}
}
</cfscript>

Conclusion

That's it! cfbreak is highly useful for flow control and instances where you need to halt processing in a loop.

Created: July 17, 2023

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.