start learning
Image 1

Switch statement

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.


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.";
}
 


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.";
}
 


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.";
}
 


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.