Skip to content

2 Ways to Implement "OR" Logical Operation in Switch Cases

There are two ways to implement the purpose of using OR logical operators in a switch case.

  1. 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":
  2. <?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!
  3. The second way is to evaluate case conditions to a Boolean value:
  4. <?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 *