Switch Statement (PHP): Unterschied zwischen den Versionen
(Die Seite wurde neu angelegt: „ = Verwendung = We often want to compare a value, expression, or variable against many different possible values and run different code depending on which it…“) |
|||
| Zeile 57: | Zeile 57: | ||
[[Kategorie:Backend-Entwicklung]] | [[Kategorie:Backend-Entwicklung]] | ||
[[Kategorie:PHP]] | [[Kategorie:PHP]] | ||
[[Kategorie:Kontrollstrukturen (PHP)]] | |||
Aktuelle Version vom 12. September 2021, 11:21 Uhr
Verwendung[Bearbeiten]
We often want to compare a value, expression, or variable against many different possible values and run different code depending on which it matches. We can use a series of if/elseif statements which use the identical operator (===) or we can use a switch statement—an alternate syntax.
Code Snippet[Bearbeiten]
switch ($variable){
case "A":
echo "Terrific";
break;
case "B":
echo "Good";
break;
case "C":
echo "Fair";
break;
default:
echo "Invalid grade";
}
Beispiele[Bearbeiten]
Bewertung Hausarbeit[Bearbeiten]
We wrote some code with a switch statement to print a string based on a student’s letter grade:
switch ($letter_grade){
case "A":
echo "Terrific";
break;
case "B":
echo "Good";
break;
case "C":
echo "Fair";
break;
case "D":
echo "Needs Improvement";
break;
case "F":
echo "See me!";
break;
default:
echo "Invalid grade";
}
We begin the keyword switch followed by the value (or expression) we’ll be comparing—in this case, $letter_grade. We provide possible matches for the expression with the keyword case, the potential matching value, and the colon. For each case, we provide code that should run if that case matches. After each case, we include the keyword break to break out of the switch statement. We can provide a default that should run if none of the provided cases match.
A switch statement is a good example of code that might be preferable not because it’s shorter, but rather because it clearly indicates the purpose of the code; when looking at a switch statement we can quickly identify the important aspects of the code; this makes it easier to understand, extend, and debug.