"Switch" Statement - Meeting 9

"switch" statement is the alternative way to the multiple "if..elseif" conditions and can be shorter way to code than "if..elseif". The regular scripts applying "switch" staement is like this:

switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement has been encountered hitherto
}

a switch statement will inspect expression by expression in a list of expression, and fire only one statement which is a match.

It is important to include a break statement at the end of any code that will be executed as part of a case statement. Without a break statement, the program flow will continue to the next case statement and ultimately to the default statement. In most cases, this will result in unexpected behavior, likely incorrect!

try a script below and save it as eight.php

<?php
$greeting = "morning"; //you may change to "afternoon" or "evening"
switch ($greeting) {
case "morning":
echo "Good morning";
break;
case "afternoon":
echo "Good afternoon";
break;
case "evening":
echo "Good evening";
break;
default:
echo "I don't know what to say but good $mood anyway.";
break;
}
?>

we initialize a variable $greeting with a value "morning". "switch" will evaluate each "case" and if find a match, it will be executed. In this case the result is "Good morning". Yet if we change the value of the variable $greeting to "afternoon" or "evening" the result will change accordingly.

No comments: