The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.
The switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it does not only execute the code corresponding to that case statement but also executes all the subsequent case statements till the end of the switch block automatically.
To prevent this add a break statement to the end of each case block. The break statement tells PHP to break out of the switch-case statement block once it executes the code associated with the first true case.
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
<?php
$days= "sunday";
switch ($days) {
case "sunday":
echo "Today Is Sunday !";
break;
case "monday":
echo "Today Is Sunday !";
break;
case "tuesday":
echo "Today Is Tuesday!";
break;
case "wednesday":
echo "Today Is Wednesday!";
break;
case "thursday":
echo "Today Is Thursday!";
break;
case "friday":
echo "Today Is Friday!";
break;
case "saturday":
echo "Today Is Saturday!";
break;
default:
echo "You Have Enter Wrong Days !";
}
?>
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning