W3docs

How to Use "or" in Switch Case in PHP

In this snippet, you will figure out how to use the "or" operator in a switch case in PHP. Read on, check out and try the examples.

Sometimes it is necessary to use switch cases in PHP. Here, we will show you two ways to simulate an "or" condition in a switch statement.

How to handle multiple values using case fall-through

In the example below, we demonstrate a switch case that handles multiple values by stacking case labels (fall-through).

php use switch case "or"

<?php

$option = 1;
switch ($option) {
  case 1:
  case 2:
    echo "The option is either 1 or 2.";
    break;
}

php use switch case "or", output

The option is either 1 or 2.

Use the “or” operator in switch case

Now, let’s see another example of using a logical expression in a switch case:

php use "or" operator in switch case

<?php

$option = 1;
switch ($option) {
  case $option == 1 || $option == 2:
    echo 'The option is either 1 or 2';
    break;
}

php use "or" operator in switch case, output

The option is either 1 or 2

Note: While expressions in case labels work, stacking case labels (fall-through) is generally preferred for readability and performance.

About Operators in PHP

Symbols that tell the PHP processor to act in a specific way are called operators. Generally, PHP operators are classified as follows:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Incrementing and Decrementing operators
  • Logical operators
  • String operators
  • Array operators
  • Spaceship Operator

Logical Operators in PHP

PHP supports standard logical operators. They work by first converting their operands to boolean values, then performing the respective comparison.

The logical operators are <kbd class="highlighted">&&</kbd>, <kbd class="highlighted">||</kbd>, <kbd class="highlighted">xor</kbd>, <kbd class="highlighted">!</kbd>, <kbd class="highlighted">AND</kbd>, and <kbd class="highlighted">or</kbd>.

These operators are mainly used for combining conditional statements.