Definition:
It controls a single block of code from various options based on the value of a variable.
It works like an if–else–if ladder.
When a condition is satisfied, the corresponding case runs, and the program exits that case using a break statement.
If a break is missing, it continues to go to the case (fall-through) one by one until it reaches a break or default.
If no case matches, the default block executes, and the program exits from the switch statement.
Now you will clearly understand the code logic with the help of the flowchart.
Switch Statement Flowchart:
You write the program
|
Then you will check the value that is in the switch statement.
|
It goes one by one through the case statements
|
If the value matches any case statements
|
execute the code of that block
|
If a break appears, then it stops that block.
|
If no case matches,
|
The default block will run.
|
Execute the code
|
End the program
Syntax:
switch (variable) {
case value1:
// It runs the code when the switch value matches from the case value1.
break;
case value2:
// It runs the code when the switch value matches from the case value2.
break;
case value3:
// It runs the code when the switch value matches from the case value3.
break;
Default:
// code to execute when none of the above matches
}
Example:
<?php
$word = "A";
switch ($word) {
case "A":
echo "A";
break;
Case "a":
echo "a";
break;
Case "c":
echo "c";
break;
Default:
echo "You have not found any condition where word = 'A' from the above cases.";
}
?>
Output:
A
