Avicinnian
Avicinnian

Reputation: 1830

A multi-conditional switch statement?

This is something that I haven't seen in the PHPdoc for switch() so I'm not sure if it's possible, but I'd like to have a case which is multi-conditional, such as:

switch($this) {
   case "yes" || "maybe":
      include "filename.php";
      break;
   ... 
}

Is this valid syntax/is this even possible with a switch() statement?

Upvotes: 0

Views: 283

Answers (5)

animuson
animuson

Reputation: 54729

Sure, just specify two cases without breaking the first one, like so:

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}

If you don't break a case, then any code for that case is run and continues on to execute additional code until the execution is broken. It will continue through all cases below it until it sees a break.

Upvotes: 0

tdammers
tdammers

Reputation: 20721

You can do this with fall-through:

switch ($this) {
    case "yes":
    case "no":
        include "filename.php";
        break;
}

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60007

Should be

switch($this) { 
   case "yes":
   case "maybe": 
      include "filename.php"; 
      break; 
   ...  
} 

Upvotes: 0

Pekka
Pekka

Reputation: 449485

Is this valid syntax/is this even possible with a switch() statement?

No and no. The expression will be evaluated as ("yes" or "maybe"), which will result in true. switch will then test against that result.

You want to use

case "yes":
case "maybe":
// some code
break;

Upvotes: 2

Gary Willoughby
Gary Willoughby

Reputation: 52498

Usually you'd just use case fall-through.

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}

Upvotes: 8

Related Questions