The switch Statement PHP

An alternative to if-elseif-else structures is the switch statement, which works on the assumption that you compare a single expression to a set of possible values.3 demonstrates the structure of a switch statement.

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. 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. I've recoded 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

Covering All Cases with em>switch

** Get today's weekday name
$english_Day = date("l");
** Find the today's German name
case "Monday":
$deutsch_Day = "Montag";
case "Tuesday":
$deutsch_Day = "Dienstag";
case "Wednesday":
$deutsch_Day = "Mittwoch";
case "Thursday":
$deutsch_Day = "Donnerstag";
case "Friday":
$deutsch_Day = "Freitag";
case "Saturday":
$deutsch_Day = "Samstag";
// It must be Sunday
$deutsch_Day = "Sonntag";
** Print today's English and German names
print("<H2>German Lesson: Day of the Week</H2>\n");
print("In English: <B>$english_Day</B>.<BR>\n");
print("In German: <B>$deutsch_Day.</B><BR>\n");

is much more useful than in other languages. If you have experience with BASIC, you might wonder if PHP's switch statement allows cases to contain ranges. It doesn't. It's probably best to code this situation with an if-elseif-else statement.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics