...

View Full Version : Using if statement with switch/case



ptmuldoon
02-28-2007, 11:28 PM
Is it possible to add an if statement inside of switch case? Below is a small piece of a pretty long switch statement that has about 12 different cases. But I only want it to change/switch cases if certain conditions are met for each particular case.

Can I just add an if statement within the case?


switch($current_state){
case 'forcetrade': $next_state = 'forceplace';
break;
case 'forceplace': $next_state = 'attacking';
break;
}

bcarl314
02-28-2007, 11:38 PM
Yep, you can do all sorts of fun stuff...



switch($somevar) {
case "option1":
case "option2":
//this will run for options 1 and 2
if($something == 2) {
//do for 2
}
else {
//do for not 2
}
break;
case "option3":
//option 3
break;
default:
//everything else, this is a catch all
}


I think you can even do things like <4 for your cases as well, but I've never tried it.

ptmuldoon
03-01-2007, 12:34 AM
Thanks. Then if I understand correctly, I think the below code is correct?

case 'initial':
if ($game_capital == Yes){
$next_state = 'capital';
} else {
$next_state = 'inactive';
}
break;
case 'capital': $next_state = 'inactive';

I ask because I haven't gotten my $next_state variable to work correctly. If the above is correct, than I likely need to amend the code somewhere else. Sort of a trial and error on my part to implement some new stuff.

Fumigator
03-01-2007, 12:49 AM
Strings (such as your string 'Yes') must be enclosed in quotes. If you are trying to set a boolean value, use TRUE or 1.

neillglobal
03-01-2007, 03:21 AM
This is a question I'd like to know the answer to aswell. I understand what you're trying to do.

If your $xxxstatexxx changes are sequential then you can just run the switch without breaks, and so the switch begins to run the code at certain points depending on the condition. I get that... no problem.... BUT what if you want to skip the next case go to another one x cases down the line..... That's what I want to know. That would be useful.

aedrin
03-01-2007, 04:30 PM
If you forget a break (on purpose or not), then the next case statements will not be evaluated. It will automatically fall through and execute the code. Otherwise the break statement wouldn't be necessary.


BUT what if you want to skip the next case go to another one x cases down the line..... That's what I want to know. That would be useful.

You can't skip X cases from within a case.

It sounds to me like you need a different setup. Consider using a for/while statement with a switch to achieve what you need. It depends on your situation though.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum