PHP Switch Statements With Examples

PHP Switch Statements Tutorial With Examples


In PHP, we use a switch statement for the execution of one statement by specifying multiple conditions. It is an alternative to the if-else statement. Both statements are serving the same purpose as conditional statements.
The switch statement in PHP is also known as a switch-case. Different blocks of code are executed for a different number of cases along with the default code block with the switch-case statement.
PHP Switch Case Syntax:
 
switch(expression){
    case name1:
        // Execute this code when expression=name1
        break;
    case name2:
        // Execute this code when expression=name2
        break;
    ...
    default:
        // Default statement will be executed if none of the cases are matched with the expression
}

In the Switch block, we compare the expression with each of the case’s values. We can use a break statement after each case for not letting the whole code be executed. The code will run until it finds the true case to be executed. The break statement is optional.
If there is no true match for switch expression and any of the cases, PHP executes a default code block.
We evaluate the switch conditional statement for once only. Afterward, each case’s value is matched with the value of the expression in the Switch block. In the output, it will either execute the associated code or the default block of code.

For Example :

Output: Number is equal to 10