views:

112

answers:

5

I am trying to get a variable on my page to equal the result of a switch I have.

This is the code:

$payment_method = switch ($cardtype) {
case "visa" : echo "VSA"; break;
case "mastercard" : echo "MSC"; break;
case "maestro" : echo "MAE"; break;
case "amex" : echo "AMX" ; break;
default : echo "Please specify a payment method!"; break;
};

How can I get $payment_method to equal the result of this????

So far I recieve an error:

Parse error: syntax error, unexpected T_SWITCH in /var/www/account/credits/moneybookers/process.php on line 65
A: 

You can't use the switch construct this way. You would have to assign $payment_method within the case parts.

In your case, seeing as you're echo ing anyway, you can just remove $payment_method = and it should work.

What would be much, much easier, though, is putting all the stuff into an array:

$payment_methods = array(
  "visa" => "VSA",
  "mastercard" => "MSC",
  "maestro" => "MAE",
  "amex" => "AMX"
);

if (!array_key_exists($cardtype, $payment_methods))
 echo "Please specify a payment method!";
else
 echo "Your method: ".$payment_methods[$cardtype];
Pekka
+2  A: 

You should do:

$payment_method = '';

switch ($cardtype) {
  case "visa" : $payment_method = "VSA"; break;
  case "mastercard" : $payment_method = "MSC"; break;
  case "maestro" : $payment_method = "MAE"; break;
  case "amex" : $payment_method = "AMX" ; break;
}

if (strlen($payment_method))
{
  echo $payment_method;
}
else
{
  echo "Please specify a payment method!";
}
Web Logic
default : $payment_method = "Please specify a payment method!"; // with this implementation it will be impossible to get is payment method valid or not.
zerkms
@zerkms: right, fixed main, please consider your down vote. Thanks
Web Logic
@Wed Logic: fixed ;-) btw, he will get notice with this code, when $cardtype is invalid
zerkms
@zerkms: What he would notice, could not get you?
Web Logic
now - nothing. i have commented the revision #2 without if(strlen()), which you have added later ;-)
zerkms
A: 

You should assign the value within the switch:

switch ($cardtype) {
    case "visa":
        $payment_method = "VSA";
    break;
    case "mastercard":
        $payment_method = "MSC";
    break;
    case "maestro":
        $payment_method = "MAE";
    break;
    case "amex":
        $payment_method = "AMX";
    break;
    default:
        echo "Please specify a payment method!";
    break;
};
salathe
+5  A: 

do in this way:

$types = array('visa' => 'VSA', 'mastercard' => 'MSC', 'maestro' => 'MAE', 'amex' => 'AMX');
if (isset($types[$cardtype])) {
    $payment_method = $types[$cardtype];
} else {
    echo 'Please specify a payment method!';
}
zerkms
A: 

Use arrays!

$types = array("visa"       => "VSA",
               "mastercard" => "MSC",
               "maestro"    => "MAE",
               "amex"       => "AMX");

$type = $types[$cardtype] or echo "Please specify a payment method!";
Eric