PHP Switch

In this lesson, you will learn about the Switch Statement in PHP, its usage, and examples to better understand the topic.


PHP Switch Statement

The Switch Statement is similar to the if…elseif…else statement we discussed in the previous lesson. It executes only one block of code depending on the condition’s value. If no condition is encountered, the default code block will be executed.

However, the Switch statement is much clearer if you validate too many conditions.


Basic Syntax of Switch Statement

switch (var) {
case control1:
 block of code will be processed if var = control1;
break;
case control2:
 block of code will be processed if var = control2;
break;
case control3:
 block of code will be processed if var = control3;
break;
default:
 block of code will be processed if var is different from all controls;
}
"Switch (...) { ... }" is the control structure block code
"case value: case ..." which is the code blocks to be executed depending on the value matches
"default" condition value: is the code block to be executed if no value matches the condition.
Note
The switch statement requires the break keywords to exist if a condition is met. Otherwise, all cases will be executed.

Syntax of the Switch Statement

 

Example of Switch Statement (With and without the break keyword)

<?php
echo "PHP *** Switch Statement*** ";
echo "<br>";
echo "<br>";
echo "****** Example (1)******* ";
echo "<br>";
$luxuryCars = "Volvo";
switch ($luxuryCars)
{
    case "Audi":
        echo "Congratulation!!Your won Audi luxury car!";
    break;
    case "Ferrari":
        echo "Congratulation!!Your won Ferrari luxury car!";
    break;
    case "Volvo":
        echo "Congratulation!!Your won Volvo luxury car!";
    break;
    default:
        echo "Sorry, better luck next time!";
}
echo "<br>";
echo "<br>";
echo "****** Example (2)******* ";
echo "<br>";
$number = 100;
echo " Number = ", $number, "</br>";
echo "<br>";
echo " Switch statement without break keyword; All cases will be processed";
echo "<br>";
//In case no break is written after case , all the cases will be executed
switch ($number)
{
    case 100:
        echo " ist the case is executed!";
        //break;
        
    case 200:
        echo "2nd case is executed!";
        //break;
        
    default:
        echo "Default executed";
}
?>

Output

PHP *** Switch Statement***

****** Example (1)*******
Congratulation!!Your won Volvo luxury car!
****** Example (2)*******
Number = 100

Switch statement without break keyword; All cases will be processed
ist the case is executed!2nd case is executed! Default executed

This concludes the PHP Switch Statement lesson. In the next lesson, we will jump to learn a different topic in the PHP programming language, loops!