douruye5092 2017-07-14 08:50 采纳率: 100%
浏览 15
已采纳

在向数组添加键之前检查变量是否已设置 - PHP

I'm using the Stripe API like so:

$coupon = $_POST["coupon"];

$subscription = \Stripe\Subscription::create(array(
  "customer" => $customer->id,
  "plan" => $plan,
  "coupon" => $coupon,
));

This works great when $coupon is set and it's a valid coupon code. If I leave it blank (i.e., customer didn't include a coupon code in form submitted), Stripe throws an error. If I include a coupon code that doesn't exist in Stripe, it throws an error.

So, the question is, how do I build this array to NOT have the coupon key when the variable $coupon is empty?

  • 写回答

3条回答 默认 最新

  • doujupa7567 2017-07-14 08:55
    关注
    $payment_data = array(
      "customer" => $customer->id,
      "plan" => $plan,
    );
    if (!empty($_POST['coupon'])) {
        $payment_data["coupon"] = $_POST['coupon'];
    }
    
    $subscription = \Stripe\Subscription::create($payment_data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部