This PHP example demonstrates how to use the switch statement to handle multiple conditions for a variable. It shows how different case labels can be grouped to execute the same block of code, which is useful when multiple values require the same output or logic. Specifically, the code checks the value of $i and:
0, 1, or 2$i is 3$i doesn’t match any caseThe break statement is used to prevent fall-through to other cases after a match is found.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
switch ($i) checks the value of the variable $i and matches it against the cases provided.case 0:, case 1:, and case 2: are grouped together without a break between them, which means if $i is 0, 1, or 2, it will execute the same block of code.
i is less than 3 but not negativebreak; statement stops the switch-case execution after matching case 0/1/2.case 3: is a separate case that will print i is 3 if $i == 3.$i = 1, output will be: i is less than 3 but not negative$i = 3, output will be: i is 3$i = 5, there is no matching case, so it will output nothing