switch statements

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
kcpaige89
Forum Newbie
Posts: 6
Joined: Sat May 12, 2007 4:13 pm

switch statements

Post by kcpaige89 »

In every example of the switch() function I have seen, there is only one variable. Can switch do many variables.

For Example:

Code: Select all

switch($var1, $var2, $var3){

case: blue, furry, peach;

echo "you have a blue furry peach";
break;

default:
echo "you don't have a blue furry peach"
break;
}
This example is minimal but I want to apply that technique in a different function.

If this cannot be done does anyone have any other suggestions?

My only thought would be:

Code: Select all

<?php
$var1="blue";
$var2="furry";
$var3="peach";
if ($var1=="blue" && $var2=="furry" && $var3=="peach")
  echo "You have a blue furry peach."; 
else
  echo "You don't have a blue furry peach"; 
?>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

$v = array("blue", "furry", "peach");

switch($v) {
	case array("blue", "furry", "peach"):
		echo "you have a blue furry peach";
		break; 
	default:
		echo "you don't have a blue furry peach";
		break;
}
kcpaige89
Forum Newbie
Posts: 6
Joined: Sat May 12, 2007 4:13 pm

Post by kcpaige89 »

That should work with GET variables correct?

Code: Select all

$v = array("_$GET['color']", "_$GET['state']", "_$GET['fruit']");

switch($v) {
        case array("blue", "furry", "peach"):
                echo "you have a blue furry peach";
                break;
        default:
                echo "you don't have a blue furry peach";
                break;
}
or would it have to be:

Code: Select all

$_GET['color']=$color
$_GET['state']=$state
$_GET['fruit']=$fruit
$v = array($color, $state, $fruit);

switch($v) {
        case array("blue", "furry", "peach"):
                echo "you have a blue furry peach";
                break;
        default:
                echo "you don't have a blue furry peach";
                break;
}
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

You have many basic errors in both pieces of code. Basically, yes, it will work with any type of variable.

Your first snippet is the better of the two, but could be done better like this:

Code: Select all

switch(array($_GET['color'], $_GET['state'], $_GET['fruit'])) {
        case array("blue", "furry", "peach"):
                echo "you have a blue furry peach";
                break;
        default:
                echo "you don't have a blue furry peach";
                break;
}
Post Reply