douruye5092 2017-07-14 16: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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了