简体   繁体   中英

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

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($otherVar != 0){ // Any conditional, it is irrelevant
     //Go to case y;
  }else{
    //case a
  }
 break;
   case 'b':
     //case b code
  break;
   case 'c':
     if($otherVar2 != 0){ // Any conditional, it is irrelevant
        //Go to case y;
     }else{
       //case c
     }
  break;
   .
   .
   .
   case 'x':
     //case x code
  break;
  case 'y':
   //case y code
  break;

  default:
  // more code
  break;
}

Is there any GOTO option, I red somewhere about it but can't find it, or maybe another solution? Thanks.

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

?>

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

case 'x' :
    if ($otherVar == 0) {
        break;
    }
case 'y' :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM