douzhaiya3968 2019-04-09 19:02
浏览 7
已采纳

选择存在的第一个变量的简单方法

Is there a simple way to input a couple variables and return the first one that exists?

For example, either $_POST['a'][$field] or $_POST['b'][$field] will exist – only one or the other, never both.

I want to assign whichever variable exists to a variable.

I was hoping for a syntax like this:

$field = $_POST['a'][$field] or $_POST['b'][$field];

but this will only return $_POST['a'][$field] (if it exists) or NULL

And I do know that I can do:

if(isset($_POST['a'][$field])){
    $field = $_POST['a'][$field];
} else {
    $field = $_POST['b'][$field];
}

but I was wondering if there is something more simple that I am not thinking of.

  • 写回答

1条回答 默认 最新

  • dslfjrmz70457 2019-04-09 19:08
    关注

    You can use the null coalesce operator. It can be chained it as many times as you need, so you can also have a default value if neither is selected.

    $field = $_POST['a'][$field] ?? $_POST['b'][$field] ?? "default";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集