SWITCH Statements

Chapter 6 #116c - Martha's CIS 52

ASSIGNMENT/EXPLANATION

The switch statement operates similarly to the if and elseif statements, which change the flow of events after evaluating multiple statements. However, the switch statement does this by evaluating "only one expression in a list of expressions, selecting the correct one based on a specific bit of matching code." Rather than evaluating expressions as either true or false, switch statements evaluate the expressions against any number of values (the case values). The expression used to compare cases may only be a variable. Nevertheless, "if the case value is equal to the expression value, the code within the case statement is executed." NOTICE: the break statement that is used at the end of any code ends the execution of that code immediately. Without the break statement, the next case statement will be executed, even if a previous match had been found. If the optional defalut statement is reached before any previous cases are matched, the default statement will execute.

SYNTAX:

switch (expression) {  // NOTICE: expression must be inside () parentheses
    case result1:
    	// this statement executed if expression matches result1
        break;
    case result2:
    	// this statement executes if expression matches result2
        break;
    default:
    	// this statement executes if no break statements 
}
Example 116c removes the second break statement - so the default statement executes AS WELL AS the "sad" case statement.

Exercise

Awww, Don't be down!neither happy nor sad but sad.

CODE

$mood = "sad";
switch ($mood) {
case "happy":
echo "Hooray, I'm in a good mood!";
break;
case "sad":
echo "Awww, Don't be down!";
// break;
default:
echo "neither happy nor sad but $mood.";
break;
}