Skip to content
Home » Web » PHP » Logical Operation in Switch Case

Logical Operation in Switch Case

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:

Apples are sweet!

If the fruit is changed into "Bananas", it will output:

Bananas are sweet!

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:

Bananas are sweet!

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.

Leave a Reply

Your email address will not be published. Required fields are marked *