PHP: is it possible to jump from one case to another inside a switch?

前端 未结 3 1311
迷失自我
迷失自我 2021-01-11 09:31

I have a switch where in very rare occasions I might need to jump to another case, I am looking for something like these:

switch($var){
 case: \'a\'
  if($ot         


        
相关标签:
3条回答
  • 2021-01-11 09:42

    You need PHP 5.3 or higher, but here:

    Here is the goto functionality from http://php.net/manual/en/control-structures.goto.php

    <?php
    
    $var = 'x';
    $otherVar = 1;
    
    switch($var){
        case 'x':
          if($otherVar != 0){ // Any conditional, it is irrelevant
             goto y;
          }else{
            //case X
          }
         break;
    
        case 'y':
            y:
            echo 'reached Y';
          break;
    
        default:
          // more code
          break;
    }
    
    ?>
    
    0 讨论(0)
  • 2021-01-11 09:51

    How about cascading (or not) based on the extra condition?

    case 'x' :
        if ($otherVar == 0) {
            break;
        }
    case 'y' :
    
    0 讨论(0)
  • 2021-01-11 10:03

    Instead of using any tricks in swtich-case, a better logic could be the following.

        function func_y() {
         ...
        }
    
        switch($var){
         case: 'x'
          if($otherVar != 0){ // Any conditional, it is irrelevant
            func_y();
          }else{
            //case X
          }
         break;
    
          case 'y':
           func_y();
          break;
    
          default:
          // more code
          break;
        }
    
    0 讨论(0)
提交回复
热议问题