为了账号安全,请及时绑定邮箱和手机立即绑定

如何在php和print中使用if multiple语句创建变量

如何在php和print中使用if multiple语句创建变量

PHP
Cats萌萌 2023-03-26 14:21:43
我需要以下代码的帮助$selected_payment_option =  'if($payment_mode == "cod"){ echo "Cash on Delivery ";}                                        if($payment_mode == "stripe"){ echo "Stripe";}                                        if($payment_mode == "bank"){ echo "Bank";}';并希望打印为 $selected_payment_option
查看完整描述

2 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

有很多方法可以做到这一点

使用 if-else:


$payment_mode = "bank";

if($payment_mode == "cod")

  $selected_payment_option = "Cash on Delivery";

elseif($payment_mode == "stripe")

  $selected_payment_option = "Stripe";

elseif($payment_mode == "bank")

  $selected_payment_option = "Bank";

else

  $selected_payment_option = "your default value";

print($selected_payment_option)

// output: Bank

使用开关:


$payment_mode = "cash";

switch($payment_mode) {

  case "cod": $selected_payment_option = "Cash on Delivery"; break;

  case "stripe": $selected_payment_option = "Stripe"; break;

  case "bank": $selected_payment_option = "Bank"; break;

  default: $selected_payment_option = "your default value";

}

print($selected_payment_option);

// output: your default value

使用三元运算符:


$payment_mode = "stripe";

$selected_payment_option = $payment_mode == "cod" ? "Cash on Delivery "

  : ($payment_mode == "stripe" ? "Stripe" : ($payment_mode == "bank" ? "Bank" 

  : "your default value"));

print($selected_payment_option);

// output: Stripe

使用逻辑运算符:


$payment_mode = "bank";

$selected_payment_option = "your default value";

$payment_mode == "cod" && ($selected_payment_option = "Cash on Delivery") ||

  $payment_mode == "stripe" && ($selected_payment_option = "Stripe") ||

  $payment_mode == "bank" && ($selected_payment_option = "Bank");

print($selected_payment_option);

// output: Bank

使用关联数组:


$payment_modes = array("cod"=> "Cash on Delivery", "stripe"=> "Stripe", "bank" => "Bank");

$payment_mode = "cod";

$selected_payment_option = array_key_exists($payment_mode, $payment_modes) ?

  $payment_modes[$payment_mode] : "your default value";

print($selected_payment_option);

// output: Cash on Delivery


查看完整回答
反对 回复 2023-03-26
?
PIPIONE

TA贡献1829条经验 获得超9个赞

请为此类代码使用开关。它还具有捕获 $payment_mode 未设置值的情况的好处。


function getPaymentOption($payment_mode) {

    switch ($payment_mode) {

        case "cod":

            return "Cash on Delivery";

            break;

        case "stripe":

            return "Stripe";

            break;

        case "bank":

            return "Bank";

            break;

        default:

            return "unknown";

    }

}

像这样使用:


$selected_payment_option = getPaymentOption($payment_mode);


查看完整回答
反对 回复 2023-03-26
  • 2 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信