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.
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!