Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 788
multimediaxp Avatar asked Oct 08 '13 02:10

multimediaxp


People also ask

Is switch faster than if else PHP?

Due to the fact that "switch" does no comparison, it is slightly faster.

Can we use switch in PHP?

The PHP switch StatementUse the switch statement to select one of many blocks of code to be executed.

Can we use condition in switch-case PHP?

PHP doesn't support this syntax. Only scalar values allowed for cases.

How does switch work in PHP?

The switch statement compares an expression with the value in each case. If the expression equals a value in a case, e.g., value1 , PHP executes the code block in the matching case until it encounters the first break statement.


Video Answer


2 Answers

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

?>
like image 167
francisco.preller Avatar answered Sep 17 '22 19:09

francisco.preller


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

case 'x' :
    if ($otherVar == 0) {
        break;
    }
case 'y' :
like image 42
Phil Avatar answered Sep 20 '22 19:09

Phil