Implementing Conditional Logic in ColdFusion
The ColdFusion Markup Language (CFML) instructions you place in your ColdFusion scripts are processed just as they would be in any other language. The ColdFusion Application Server starts at the first line of the script and works its way sequentially through to the last line. Every command is processed unless it is part of a conditional statement. Conditional statements allow you to process or not process code, depending on the outcome of a condition you assess. Conditional statements typically use Boolean conditions, which can have only one of two possible valuesTRUE or FALSE.
The most basic form of conditional statement is the "if-then" rule. Our own behavior is governed by many such rules. For example, "If the traffic light is red, then stop the car." In this rule, you assess the condition that asks whether the traffic light is red. If it is true, you stop the car. If it isn't true, you don't stop the car. Such a rule is frequently useful in dynamic Web development. ColdFusion implements "if-then" rules through the <cfif> instruction.
A <cfif> instruction can be extended to include <cfelse> as well. Use of <cfelse> gives you some kind of recourse if the condition you're testing turns out to have a value of FALSE. Sometimes when the condition you assess is false, you want to move on to assess a second condition. ColdFusion enables you to do so by means of the <cfelseif> instruction.
Finally, you may have to assess a question or situation that has an outcome that goes beyond TRUE or FALSE values. For example, the question "What day of the week is it?" has seven possible outcomes. No Boolean condition can handle all seven possibilities. In this case, you can use <cfswitch> to set up code to be processed for each one of the seven outcomes.
In this chapter, you will
Learn how to implement if-then rules using <cfif>
Learn how to extend your if-then rules to if-then-else rules by adding <cfelse>
Learn how to extend your if-then and if-then-else rules to consider other conditions
Learn how to consider an expression with many possible values using <cfswitch>