In PHP, a "switch" statement is used to perform different actions based on the value of an expression. It's particularly useful when you have multiple conditions to check against a single variable.
Switch statement
Basic Syntax of a "switch" Statement
The basic syntax of a "switch" statement in PHP is as follows:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// Additional cases...
default:
// Code to execute if none of the cases match
}
Days of the Week
$day = "Wednesday";
switch ($day) {
case "Monday":
echo "It's the start of the week.";
break;
case "Wednesday":
echo "It's the middle of the week.";
break;
case "Friday":
echo "It's almost the weekend!";
break;
default:
echo "It's just another day.";
}
- $day represents the current day of the week.
- The "switch" statement checks the value of $day against different cases.
- When $day matches a case (in this case, "Wednesday"), it executes the code inside that case block.
- In this example, since $day is "Wednesday," it echoes "It's the middle of the week."
Grades
$grade = "B";
switch ($grade) {
case "A":
echo "Excellent!";
break;
case "B":
echo "Good job!";
break;
case "C":
echo "You passed.";
break;
default:
echo "You didn't receive a standard grade.";
}
- $grade represents a student's grade.
- The "switch" statement checks the value of $grade against different cases.
- Depending on the value of $grade, it executes the corresponding case block.
- In this example, since $grade is "B," it echoes "Good job!"
Fruit Selection
$fruit = "Apple";
switch ($fruit) {
case "Banana":
case "Apple":
case "Cherry":
echo "This is a common fruit.";
break;
case "Dragonfruit":
echo "This is an exotic fruit.";
break;
default:
echo "This is not a recognized fruit.";
}
- $fruit represents a type of fruit.
- The "switch" statement allows multiple cases to execute the same code (in this case, "Banana," "Apple," and "Cherry" are grouped together).
- If $fruit matches any of the common fruits, it echoes "This is a common fruit."
- In this example, since $fruit is "Apple," it echoes "This is a common fruit."
In each of these examples, the "if" statement checks a condition, and if the condition is true, the code inside the "if" block is executed. If the condition is false, the code inside the "else" block is executed. The "else" statement allows you to provide an alternative action to be taken when the condition is not met.
×