How to Use "or" in Switch Case in PHP

Sometimes it is necessary to use switch cases in PHP. Here, we will show you two ways of using the or operator in switch cases in PHP.

How to apply "or" without using break keyword

In the example below, we demonstrate a switch case on how to apply or without using the break keyword.

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

The output of this example will bring the following:

  The option is either 1 or 2.

Use the “or” operator in switch case

Now, let’s see another example of using the or operator in switch case:

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

The output will look as follows:

  The option is either 1 or 2

About Operators in PHP

The symbols, telling the PHP processor to act in a specific way, are called operators. Generally, the PHP operators are classified in the following way:

  • 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 in the following way: first, they convert their operands to boolean, then implement a respective comparison.

The logical operators are &&,||, xor, !,AND, or.

These operators are mainly used for combining conditional statements.


Do you find this helpful?

Related articles