Switch Statement

As long as you are able to grasp the idea that all of ColdFusion is in tags and understand how to use an if statement, switch statements aren’t too difficult to understand. The expression must be in the output tags, ## and in quotes, of course. The <cfcase> follow the expression, but they don’t need to output a variable so the ## should not be here unless you planning on putting a variable in the numbers place. Just try to think of a switch statement as one really really long or short (depending on how many cases you make) if statement. That is one long if statement with a lot of else ifs. Let’s go to an example.

    <cfset x = 3>
    <cfswitch expression="#x#">
        <cfcase value="1">
            My value is 1 <br/>
        <cfcase value="2">
            My value is 2 <br/>
        <cfcase value="3">
            My value is 3 <br/>
        <cfcase value="4">
            My value is 4 <br/>

My value is 3

Let’s break the switch statement down. We have the switch statement put in one big <cfoutput> because we are lazy and that is what lazy people do. Then, we set our variable x equal to 3. After that, we finally come to our switch statement. The <cfswitch expression=”#x#”> is where we define what variable we are going to check the cases (or ifs) against. Using our variable x, we run through the first case <cfcase value = “1”>, which is simply asking is our variable x equal to one? If it is, do everything before the closing </cfcase>. If not, skip the current <cfcase> and check the next one. So, we fail the first few cases and come to the <cfcase value=”3″>. We meet the condition and so we output “My value is 4 <br />”. Finally, we exit the switch statement. Tutorial mastered!

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Share on StumbleUpon
Digg this
Tweet about this on Twitter
Share on Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.