Switch Statement: Multiple Values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Hyarion
Forum Newbie
Posts: 12
Joined: Tue Nov 01, 2005 4:30 am
Location: South Africa

Switch Statement: Multiple Values

Post by Hyarion »

I've been learning php for a while now and really enjoying it. The only thing I would like to know is how to use (if possible) multiple values for a switch statement. I'm used to Visual Basic's Selelect statement. In VB I could do this:

Code: Select all

Select var$
case is < 20
'do something

case 20
'do something specific

case is > 20
'do something else

end select
How would one do this in PHP?

As far as I can see one would either need to use IF...ELSEIF statements or do something like this:

Code: Select all

switch ($var){
case 0:
case 1:
case 2:
...
case 19
//do something

case 20:
//do something specific

case 21:
case 22:
case 23:
...
case 30:
//do something else
}
This seems like a bit of a time consumer.

Is there a way to do this properly in PHP?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

php allows full expressions in the case condition...
Hyarion
Forum Newbie
Posts: 12
Joined: Tue Nov 01, 2005 4:30 am
Location: South Africa

Post by Hyarion »

ok, how does one use the expressions?

Code: Select all

switch($var){
case > 20:
 //does not work in my testing.

case $var > 20:
//havn't tested, is this how one uses it?

}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

although you should have tested it ;)

the second one.
Hyarion
Forum Newbie
Posts: 12
Joined: Tue Nov 01, 2005 4:30 am
Location: South Africa

Post by Hyarion »

Thank you. :wink:
Post Reply