Skip to Content

CFSwitch & CFCase Conditional Statements in CFML

In this tutorial, we'll explore the cfswitch, cfcase, and cfdefaultcase tags to create conditional statements in CFML.

What is cfswitch?

The cfswitch tag evaluates a given expression and processes the contents of a matching value passed in a cfcase tag. It can match against any simple data type and works great for instances where you have multiple conditions to check against and is a cleaner solution than evaluating a large amount of if/else statements.

Code Examples

For example, if we wanted to determine what our favorite fruit was, doing so with if/else statements gets cluttered and can slow down processing time with larger statements:

<cfset variables.fruit = "orange">

<cfif variables.fruit eq "orange">
I love oranges!
<cfelseif variables.fruit eq "apple">
I love apples!
<cfelseif variables.fruit eq "banana">
I love bananas!
<cfelse>
I don't like fruit.
</cfif>

You can see that this is cluttered and a bit redundant. With cfswitch, you can check against multiple values using a single expression:

<cfset variables.fruit = "orange">

<cfswitch expression="#variables.fruit#">
<cfcase value="orange">I love oranges!</cfcase>
<cfcase value="apple">I love apples!</cfcase>
<cfcase value="banana">I love bananas!</cfcase>
<cfdefaultdase>I don't like fruit.</cfdefaultcase>
</cfswitch>

Matching Multiple Values with cfcase

cfcase tags allow for multiple values at once separated by a comma-delimited list:

<cfset variables.fruit = "orange">

<cfswitch expression="#variables.fruit#">
<cfcase value="orange,citrus">I love oranges!</cfcase>
<cfcase value="apple">I love apples!</cfcase>
<cfcase value="banana">I love bananas!</cfcase>
<cfdefaultdase>I don't like fruit.</cfdefaultcase>
</cfswitch>

Script Syntax

Here is an example with the alternative script syntax:

<cfscript>
variables.fruit = "orange";

switch(variables.fruit) {
case "orange,citrus":
writeOutput("I love oranges!");
break;
case "apple":
writeOutput("I love apples!");
break;
case "banana":
writeOutput("I love bananas!");
break;
default:
writeOutput("I don't like fruit.");
break;
}
</cfscript>

Conclusion

The cfswitch and cfcase tag combination is a great solution for creating clean conditional statements with CFML.

Created: July 17, 2023