Jeff
Jeff

Reputation: 2862

Is it possible to use for loop inside a switch?

I'm attempting something like the following:

 switch ($p) {
    foreach ($modules as $m) {
    case '"'.$mod.'"':
    include 'modules/'.$m.'/cases.php';
    break;
    }
 }

but can't get it to work. Is it possible to use a for loop in this manner, inside a switch?

Upvotes: 3

Views: 6872

Answers (6)

Michael Borgwardt
Michael Borgwardt

Reputation: 346327

Looks like some form of Duff's device - but I don't think that's legal anywhere outside of C.

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146093

Yes and No

You need to move the foreach outside the switch or inside the case selector. I'm not sure why the switch() is even necessary. Why not just do whatever to each module without running it through a switch?

And most languages don't let you jump into inner blocks. Even when they do, it's not a good practice.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401032

I don't think you can do such a thing : immediatly a switch statement, the only thing you can use is a case or a default statement.

That is what the error you are getting is telling you, btw :

Parse error: syntax error, unexpected T_FOREACH, expecting T_CASE or T_DEFAULT or '}'

If you want a loop and a swith, you'll have to either put the loop "arround" the whole switch statement, or "inside" a case statement.

Upvotes: 0

hobbs
hobbs

Reputation: 240040

You certainly can use a loop inside a switch. You can't, however, do what you're trying to do there; it just doesn't work. And I don't see any point to it either. Why not just have an array with the module names as keys, and then do

if ($modules[$p]) {
  include $modules[$p];
} else {
  // not found...
}

or something to that effect?

Upvotes: 0

janoliver
janoliver

Reputation: 7824

I don't think it is...

Basic and shorter solution:

foreach($modules AS $m) {
    if($p == $m) {
        include 'modules/'.$m.'/cases.php';
        break;
    }
}

but the best would be:

if(in_array($p, $modules))
    include 'modules/'.$p.'/cases.php';

Upvotes: 6

Amber
Amber

Reputation: 526763

If you're wanting to do something like determine if $p is in $modules, and if so, include it, there's probably a better way to do that than a switch statement.

Upvotes: 0

Related Questions