0

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???

1
  • 2
    a couple of line breaks would make the code a lot more readable Commented May 20, 2010 at 16:03

4 Answers 4

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

echo ( isset( $types[ $cardtype ] ) ) ? $types[ $cardtype ] : 'Wrong card type';
Sign up to request clarification or add additional context in comments.

3 Comments

Using isset is shorter and faster than array_key_exists. It also has a more natural syntax.
Careful guys, there's a drive-by downvoter in the house. Make sure your shotguns are loaded.
Sorry for the delay in acceptance. Yes this has answered my question thanks Jacob
2

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

1 Comment

You could, but it can be done much more concisely with an associative array
0

Here is one way to do it:

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

And so on

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.