[php] How to use a switch case 'or' in PHP

Is there a way of using an 'OR' operator or equivalent in a PHP switch?

For example, something like this:

switch ($value) {

    case 1 || 2:
        echo 'the value is either 1 or 2';
        break;
}

This question is related to php switch-statement case

The answer is


http://php.net/manual/en/control-structures.switch.php Example

$today = date("D");

    switch($today){

        case "Mon":

        case "Tue":

            echo "Today is Tuesday or Monday. Buy some food.";

            break;

        case "Wed":

            echo "Today is Wednesday. Visit a doctor.";

            break;

        case "Thu":

            echo "Today is Thursday. Repair your car.";

            break;

        default:

            echo "No information available for that day.";

            break;

    }

If you must use || with switch then you can try :

$v = 1;
switch (true) {
    case ($v == 1 || $v == 2):
        echo 'the value is either 1 or 2';
        break;
}

If not your preferred solution would have been

switch($v) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

The issue is that both method is not efficient when dealing with large cases ... imagine 1 to 100 this would work perfectly

$r1 = range(1, 100);
$r2 = range(100, 200);
$v = 76;
switch (true) {
    case in_array($v, $r1) :
        echo 'the value is in range 1 to 100';
        break;
    case in_array($v, $r2) :
        echo 'the value is in range 100 to 200';
        break;
}

switch ($value) 
{
   case 1:
   case 2:
      echo 'the value is either 1 or 2';
   break;
}

The best way might be if else with requesting. Also, this can be easier and clear to use.

Example:

<?php 
$go = $_REQUEST['go'];
?>
<?php if ($go == 'general_information'){?>
<div>
echo "hello";
}?>

Instead of using the functions that won't work well with PHP, especially when you have PHP in HTML.


I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.


The best way might be if else with requesting. Also, this can be easier and clear to use.

Example:

<?php 
$go = $_REQUEST['go'];
?>
<?php if ($go == 'general_information'){?>
<div>
echo "hello";
}?>

Instead of using the functions that won't work well with PHP, especially when you have PHP in HTML.


I suggest you to go through switch (manual).

switch ($your_variable)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

Explanation

Like for the value you want to execute a single statement for, you can put it without a break as as until or unless break is found. It will go on executing the code and if a break found, it will come out of the switch case.


If you must use || with switch then you can try :

$v = 1;
switch (true) {
    case ($v == 1 || $v == 2):
        echo 'the value is either 1 or 2';
        break;
}

If not your preferred solution would have been

switch($v) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

The issue is that both method is not efficient when dealing with large cases ... imagine 1 to 100 this would work perfectly

$r1 = range(1, 100);
$r2 = range(100, 200);
$v = 76;
switch (true) {
    case in_array($v, $r1) :
        echo 'the value is in range 1 to 100';
        break;
    case in_array($v, $r2) :
        echo 'the value is in range 100 to 200';
        break;
}

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.


switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling through" the case block. The term exists in most languages implementing a switch statement.


Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

I suggest you to go through switch (manual).

switch ($your_variable)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

Explanation

Like for the value you want to execute a single statement for, you can put it without a break as as until or unless break is found. It will go on executing the code and if a break found, it will come out of the switch case.


Match expression (PHP 8)

PHP 8 RFC introduced a new match expression that is similar to switch but with the shorter syntax:

  • doesn't require break statements
  • combine conditions using a comma
  • returns a value

Example:

match ($value) {
  0 => '0',
  1, 2 => "1 or 2",
  default => "3",
}

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.


switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling through" the case block. The term exists in most languages implementing a switch statement.


Match expression (PHP 8)

PHP 8 RFC introduced a new match expression that is similar to switch but with the shorter syntax:

  • doesn't require break statements
  • combine conditions using a comma
  • returns a value

Example:

match ($value) {
  0 => '0',
  1, 2 => "1 or 2",
  default => "3",
}

Try with these following examples in this article : http://phpswitch.com/

Possible Switch Cases :

(i). A simple switch statement

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

Example :

switch($bar)
{
    case 4:
        echo "This is not the number you're looking for.\n";
        $foo = 92;
}

(ii). Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:

Example :

case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iii). Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Example :

case 2:

case 3:
case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iv). Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Example :

switch(true)
{
    case (strlen($foo) > 30):
        $error = "The value provided is too long.";
    $valid = false;
    break;

    case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
        $error = "The value must be alphanumeric.";
    $valid = false;
    break;

    default:
    $valid = true;
    break;
}

i think this may help you to resolve your problem.


Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Use this code:

switch($a) {
    case 1:
    case 2:
        .......
        .......
        .......
        break;
}

The block is called for both 1 and 2.


http://php.net/manual/en/control-structures.switch.php Example

$today = date("D");

    switch($today){

        case "Mon":

        case "Tue":

            echo "Today is Tuesday or Monday. Buy some food.";

            break;

        case "Wed":

            echo "Today is Wednesday. Visit a doctor.";

            break;

        case "Thu":

            echo "Today is Thursday. Repair your car.";

            break;

        default:

            echo "No information available for that day.";

            break;

    }

switch ($value) 
{
   case 1:
   case 2:
      echo 'the value is either 1 or 2';
   break;
}

Use this code:

switch($a) {
    case 1:
    case 2:
        .......
        .......
        .......
        break;
}

The block is called for both 1 and 2.


Try with these following examples in this article : http://phpswitch.com/

Possible Switch Cases :

(i). A simple switch statement

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

Example :

switch($bar)
{
    case 4:
        echo "This is not the number you're looking for.\n";
        $foo = 92;
}

(ii). Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:

Example :

case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iii). Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Example :

case 2:

case 3:
case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iv). Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Example :

switch(true)
{
    case (strlen($foo) > 30):
        $error = "The value provided is too long.";
    $valid = false;
    break;

    case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
        $error = "The value must be alphanumeric.";
    $valid = false;
    break;

    default:
    $valid = true;
    break;
}

i think this may help you to resolve your problem.


switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling through" the case block. The term exists in most languages implementing a switch statement.


Note that you can also use a closure to assign the result of a switch (using early returns) to a variable:

$otherVar = (static function($value) {
    switch ($value) {
        case 0:
            return 4;
        case 1:
            return 6;
        case 2:
        case 3:
            return 5;
        default:
            return null;
    }
})($i);

Of course this way to do is obsolete as it is exactly the purpose of the new PHP 8 match function as indicated in _dom93 answer.


Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling through" the case block. The term exists in most languages implementing a switch statement.


I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.


Note that you can also use a closure to assign the result of a switch (using early returns) to a variable:

$otherVar = (static function($value) {
    switch ($value) {
        case 0:
            return 4;
        case 1:
            return 6;
        case 2:
        case 3:
            return 5;
        default:
            return null;
    }
})($i);

Of course this way to do is obsolete as it is exactly the purpose of the new PHP 8 match function as indicated in _dom93 answer.


Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript

Examples related to case

PostgreSQL CASE ... END with multiple conditions SQL Server: use CASE with LIKE SQL Server IIF vs CASE SELECT using 'CASE' in SQL SELECT query with CASE condition and SUM() GROUP BY + CASE statement SQL use CASE statement in WHERE IN clause SQL Server - Case Statement where to place CASE WHEN column IS NULL in this query Regarding Java switch statements - using return and omitting breaks in each case