Page 1 of 1

switch statements

Posted: Sun May 20, 2007 2:05 pm
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"; 
?>

Posted: Sun May 20, 2007 2:33 pm
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;
}

Posted: Sun May 20, 2007 3:05 pm
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;
}

Posted: Sun May 20, 2007 3:23 pm
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;
}