How to Use a Switch case \'or\' in PHP

In PHP, the switch-case statement does not directly support the logical OR (||) operator to combine multiple cases. However, there are several effective approaches you can use to achieve similar functionality when you need multiple values to trigger the same action.

Using If-Else Statements

Instead of using a switch statement, you can utilize if-else statements with logical "or" operators ?

<?php
$value = 2;

if ($value == 1 || $value == 2 || $value == 3) {
   // Code to be executed if $value is 1, 2, or 3
   echo "Value is 1, 2, or 3";
} elseif ($value == 4) {
   // Code to be executed if $value is 4
   echo "Value is 4";
} else {
   // Code to be executed if $value doesn't match any condition
   echo "Value is not 1, 2, 3, or 4";
}
?>
Value is 1, 2, or 3

The first condition checks if $value is equal to 1, 2, or 3. If true, it executes the code block and displays "Value is 1, 2, or 3". The elseif condition checks if $value is equal to 4. If true, it executes the corresponding code block and displays "Value is 4".

Using an Array and in_array()

Using an array and the in_array() function is another approach to achieve a similar effect to a switch case with logical "or" conditions ?

<?php
$value = 2;
$validValues = [1, 2, 3];

if (in_array($value, $validValues)) {
   // Code to be executed if $value is 1, 2, or 3
   echo "Value is 1, 2, or 3";
} elseif ($value == 4) {
   // Code to be executed if $value is 4
   echo "Value is 4";
} else {
   // Code to be executed if $value doesn't match any condition
   echo "Value is not 1, 2, 3, or 4";
}
?>
Value is 1, 2, or 3

We define an array $validValues that contains the values we want to check against. The in_array() function determines if $value exists within the array. If $value is found in the array, the corresponding code block is executed.

Using Switch with Fall-Through

You can achieve "or" functionality in switch statements by using fall-through cases without break statements ?

<?php
$value = 2;

switch ($value) {
    case 1:
    case 2:
    case 3:
        echo "Value is 1, 2, or 3";
        break;
    case 4:
        echo "Value is 4";
        break;
    default:
        echo "Value is not 1, 2, 3, or 4";
        break;
}
?>
Value is 1, 2, or 3

Cases 1, 2, and 3 don't have break statements, so execution "falls through" to the next case until it reaches the break statement after case 3.

Conclusion

Although there is no direct way to use an "or" condition within a switch statement in PHP, you can achieve similar functionality using if-else statements, array checks with in_array(), or switch fall-through cases. Choose the approach that best fits your specific requirements and code readability needs.

Updated on: 2026-03-15T10:32:29+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements