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

我需要以下代码的帮助


$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


Cats萌萌
浏览 94回答 2
2回答

慕莱坞森

有很多方法可以做到这一点使用 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

PIPIONE

请为此类代码使用开关。它还具有捕获 $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);
打开App,查看更多内容
随时随地看视频慕课网APP