Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1
Figure 3-3. The switch statement.

The root expression inside a switch statement is evaluated and then compared to each
expression following a case statement. At the end of the list of cases you can put a
default statement that works exactly like an else statement; it matches if no other case
matches.


Notice that cases don't have curly braces after them. This reveals an important difference
between if and switch. When an if block matches and is executed, control skips to the
end of the entire if statement. In Listing 3.3, if today is Tuesday, deutsch_Day is set to
Dienstag, and control jumps down to after the closing curly brace closing the else
block.


A case statement serves as a starting point for execution. The root expression is
compared to each case expression until one matches. Each line of code after that is
executed. If another case statement is reached, it is ignored. Sometimes this is useful, but
most often a break statement is used to escape from the switch statement.


Take a look at Listing 3.4. I've recoded Listing 3.3 using a switch statement. The best
argument for using switch is that it can be much easier to understand. Since PHP allows
you to compare strings, the switch statement


Listing 3.4 Covering All Cases with switch


<?
/*
Get today's weekday name
/
$english_Day = date("l");
/

Find the today's German name
*/
switch($english_Day)
{
case "Monday":
$deutsch_Day = "Montag";
break;
case "Tuesday":
$deutsch_Day = "Dienstag";
break;
case "Wednesday":
$deutsch_Day = "Mittwoch";
break;
case "Thursday":

Free download pdf