Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple condition cases inside Switch method?

Tags:

php

Is there a way to include multiple cases inside a switch method in php?

like image 956
Starx Avatar asked Apr 13 '26 09:04

Starx


2 Answers

The switch statement works by evaluating each case expression in turn and comparing the result to the switch expression. If the two expressions are equivalent, the case block is executed (within the constraints established by break/continue constructs). You can use this fact to include arbitrary boolean expressions as case expressions. For example:

<?php

$i = 3;
$k = 'hello world';

switch (true) {
    case 3 == $i and $k == 'hi there';
        echo "first case is true\n";
    break;

    case 3 == $i and $k == 'hello world';
        echo "second case is true\n";
    break;
} //switch

?>

This outputs:

second case is true

I don't use this sort of construction very often (instead preferring to avoid such complex logic), but it sometimes comes up where a complicated if-then statement might otherwise be used, and can make such snippets much easier to read.

like image 63
mr. w Avatar answered Apr 14 '26 23:04

mr. w


What's wrong with simply nesting switches?

$i = 1;
$j = 10;

switch($i) {
    case 2:
        echo "The value is 2";
        break;
    case 1:
        switch($j) {
            case 10:
                echo "Exception Case";
                break;
            default:
                echo "The value is 1";
                break;
        }
        break;
    default:
        echo "Invalid";
        break;
}
like image 39
Mark Baker Avatar answered Apr 15 '26 00:04

Mark Baker