如果switch中的所有情况都为true,则如何循环遍历这些情况


How to loop through all cases in switch if they are all true

我有一个包含3种情况的switch语句,如下所示:

switch($date) {
 case 1:
   echo "";
 break; 
 case 2:
  echo "";  
 break;
case 3:
 echo'';
break;   
default:            
 echo '';
break;
}

我想知道,如果所有的案例都是真的,是否有办法循环所有的案例。但是使用break,因为如果我不使用它,这些案例就无法正常工作。那么有办法吗???

如果您想查看有关变量的多个情况是否为真,则不应该使用switch,因为一旦其中一个情况为真,switch语句就会被截断(即,它不会继续查看其他情况是否也适用于该变量)。

如果你的目标是测试一个变量是否有多件事是真的,只需使用If语句:

if ($date == X && $date == Y && $date == Z) {
    // Do something since all the conditions are met
}

另一种可能性是像这样"失败":

switch ($variable) {
    case 0:
        // Do something to (some) variable to indicate this case applies
    case 1:
        // Do something to (some) variable to indicate this case also applies
    case 2:
        // Do something to (some) variable to indicate this case also applies
        echo "WHATEVER YOU WANT TO ECHO"
        break;
}