Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get variable to equal value of switch

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
like image 292
user342391 Avatar asked May 23 '10 14:05

user342391


People also ask

Can we use condition in switch case PHP?

Each condition you want to match has a case where you pass in the variable you want to match. Within the case, you put the code you want to run if the condition matches. Then you need to add a break, otherwise the code will continue to check for matches in the rest of the switch statement.

Which is faster if else or switch in PHP?

Speed: A switch statement might prove to be faster than ifs provided number of cases are good.

How does switch work in PHP?

The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.

How are variables declared in PHP?

A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


1 Answers

Use arrays!

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

$type = @$types[$cardtype] or echo "Please specify a payment method!";
like image 55
Eric Avatar answered Oct 21 '22 08:10

Eric