What You Must Know About ColdFusion Flow-Controls - Which way to go?
(Page 3 of 6 )
The conditional tags <cfswitch/>, <cfcase>, and <cfdefaultcase>In the previous case of the <cfelseif> tag it was possible to test for two conditions which provided one of two paths to take, depending on the outcome of the test. This is clearly not the correct approach if you need to test for several conditions.
The <cfswitch/> tag allows you to have this possibility in a much more elegant manner. Depending on the outcome of the test, you have the opportunity to proceed in a number of ways, each way decided by a <cfcase> tag. What if none of the conditions you tested gave a positive outcome? Well, no need to be disheartened; there is a <cfdefaultcase> case that will take care of how you should proceed if none of the conditions were satisfied. The <cfdefaultcase> is optional, and its position in the <cfswitch/> block need not be at the end before the </cfswitch> tag. The <cfcase> and <cfdefaultcase> tags are always used within the <cfswitch/> tag
Example 7<cfset test="C++">
<cfswitch expression=#test#>
<cfcase value="vb">
You are a Visual Basic Guy
</cfcase>
<cfcase value="C++">
You are a C++ Programmer
</cfcase>
<cfcase value="sql">
You are a SQL Programmer
</cfcase>
<cfdefaultcase>
I don't think you are a VB, C, or SQL Programmer
</cfdefaultcase>
</cfswitch>
The displayed output by browsing the above file is as shown next. The declared value of test found a match for the case whose value was C++.
You are a C++ Programmer
Example 8
The variable name is switched around until it matches with the constant value of one of the case statements, and when the match is found the line/lines under that case is/are processed. If break is not in place, the immediately following case will be tested. The default is usually the last statement before the switch ends, but could be anywhere. If it's not in the end, it must be followed by a break.
Please refer to the Macromedia site for any unresolved issues and other restrictions with the usage of Switch. Although end switch has been added as required by the documentation, it appears to be optional, i.e., the code runs even without this.
<cfscript>
name="John";
switch(name){
case "Tom":
writeoutput ("Name is Tom");
break;
case "June":
writeoutput ("Name is June");
break;
case "John":
writeoutput ("Name is John");
break;
default:
writeoutput ("Name unknown");
}//end switch
</cfscript>
The displayed output when you run this code is:
Name is John
Next: Keep looking until you find >>
More ColdFusion Articles
More By Jayaram Krishnaswamy