There are two ways to implement the purpose of using OR logical operators in a switch case.
Evaluation at SWITCH
The first way is to take advantage of fall through of a switch case, for example, if we'd like to know the nature of apples, we use a switch case with no content in case "Apples".
<?php
$fruit = "Apples";
$message = "";
switch ($fruit) {
case "Apples" :
case "Bananas" :
$message .= $fruit . " are sweet!"
break;
case "Peaches" :
$message .= $fruit . " are juicy!"
break;
}
echo $message;
?>
If the case "Apples" matches, it will fall through to case "Bananas", execute the code, and then escape from the switch block. The output will be:
If the fruit is changed into "Bananas", it will output:
Evaluation at CASE
The second way is to evaluate case conditions to a Boolean value.
<?php
$fruit = "Bananas";
$message = "";
switch (true) {
case $fruit == "Apples" || $fruit == "Bananas" :
$message .= $fruit . " are sweet!"
break;
case $fruit == "Peaches" :
$message .= $fruit . " are juicy!"
break;
}
echo $message;
?>
The output will be:
You can use any comparison operators ==, !=, >, < ... or logical operators &&, ||, etc. In my opinion, the second way is more flexible and easy to understand for developers. You can try it by yourself.