Home » Tutorials » ColdFusion » Switch Statement

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/>
Result 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!

Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Switch Statement". After Hours Programming. Accessed on July 4, 2024. https://www.afterhoursprogramming.com/tutorial/coldfusion/switch-statement-cf/.

  • Stewart, Suzy. "Switch Statement". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/coldfusion/switch-statement-cf/. Accessed 4 July, 2024.

  • Stewart, Suzy. Switch Statement. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/coldfusion/switch-statement-cf/.

Leave a Comment

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