doudao7511 2017-11-18 08:17
浏览 21
已采纳

如何检查多个变量并初始化非空变量?

I have a form with multiple inputs for one value which have similar names. something like this:

isset($_GET['name1'])
isset($_GET['name2'])
isset($_GET['name3'])

Always, either only one of them is true or none of them. And here is my code:

$name = '';
if( isset($_GET['name1']) ){
    $name = $_GET['name1'];
} else if ( isset($_GET['name2']) ) {
    $name = $_GET['name2'];
} else if ( isset($_GET['name3']) ) {
    $name = $_GET['name3'];
}

echo $name;

My code works as well. But I guess I can do that without those conditions. Any idea how can I write that logic more clean?

  • 写回答

4条回答 默认 最新

  • duai5344 2017-11-18 08:21
    关注

    You can use a loop:

    for ($i = 1; $i <= 3; $i++) {
        if (isset($_GET["name$i"])) {
            $name = $_GET["name$i"];
            break;
        }
    }
    

    Using the PHP 7 coalescing operator, you can write:

    $name = $_GET["name1"] ?? $_GET["name2"] ?? $_GET["name3"] ?? "";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys