tags:

views:

56

answers:

4

I am trying to echo certain values if the variable $cardtype ==

     $paymentmethod = if( $cardtype == 'visa' ) echo 'VSA'; 
elseif ( $cardtype == 'mastercard' ) echo 'MSC'; 
elseif ( $cardtype == 'mastercard' ) echo 'MSC'; 
elseif ( $cardtype == 'maestro' ) echo 'MAE'; 
elseif ( $cardtype== 'amex' ) echo 'AMX';

How would I do this???

A: 

Here is one way to do it:

switch($cardtype) {
 case 'visa':
  echo 'VSA';
  break;
 case 'mastercard':
  echo 'MSC';
  break;
}

And so on

baloo
+2  A: 

You could use a function containing a switch statement for this:

function GetPaymentMethod( $cardtype )
{
    switch( $cardtype )
    {
    case 'visa':
      return 'VSA';
    case 'mastercard':
      return 'MSC';
    case 'maestro':
      return 'MAE';
    case 'amex':
      return 'AMX';
    default:
      return '<Invalid card type>';
    }
}

Test:

echo GetPaymentMethod( 'visa' ); // VSA
lamas
You *could*, but it can be done much more concisely with an associative array
Brian
+5  A: 
$types = array( 'visa' => 'VSA', 'mastercard' => 'MSC', 
                'maestro' => 'MAE', 'amex' => 'AMX' );

echo ( isset( $types[ $cardtype ] ) ) ? $types[ $cardtype ] : 'Wrong card type';
Jacob Relkin
+1 nice, was *just* typing this!
karim79
@karim79 thanks!
Jacob Relkin
Using `isset` is shorter and faster than `array_key_exists`. It also has a more natural syntax.
ryeguy
@ryeguy, thanks! I updated the code.
Jacob Relkin
Careful guys, there's a drive-by downvoter in the house. Make sure your shotguns are loaded.
karim79
OP, is this good enough for an "accepted answer"?
Jacob Relkin
Sorry for the delay in acceptance. Yes this has answered my question thanks Jacob
A: 

for your own code, you have to just remove strange $paymentmethod = from the beginning.

if( $cardtype == 'visa' ) echo 'VSA';  
elseif ( $cardtype == 'mastercard' ) echo 'MSC'; 
elseif ( $cardtype == 'maestro' ) echo 'MAE'; 
elseif ( $cardtype== 'amex' ) echo 'AMX';

it will work too.

Col. Shrapnel