开发者

How to add multiple condition cases inside Switch method?

开发者 https://www.devze.com 2023-01-02 07:23 出处:网络
Is ther开发者_StackOverflow中文版e a way to include multiple cases inside a switch method in php?The switch statement works by evaluating each case expression in turn and comparing the result to the s

Is ther开发者_StackOverflow中文版e a way to include multiple cases inside a switch method in php?


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.


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;
}


Yes it is possible

Here is an example to start with

<?
      $i = 1;
      $j = 10;

      switch($i) {
            case "2":
                   echo "The value is 2";
                   break;
            case ($i==1 && $j==10):
                   echo "Your exceptional Switch case is triggered";
                   break;
            default:
                   echo "Invalid";
                   break;
     }
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消