douyanzhou1450 2014-04-26 11:31
浏览 466
已采纳

PHP如果未定义,则在GET值上设置默认值

I have the below form where I am putting in a value in my field which is different depending if there is anything to GET or not.

What I have works but I am wondering if there is more efficient way of coding this, as my real form will have around 10 input fields and I don't want to be adding 6 lines of code each time I add a new input field?

        <?php
        if (isset($_GET["name"])) {
            $name = $_GET["name"];
        }
        else {
            $name = 0;
        }

        if (isset($_GET["type"])) {
            $type = $_GET["type"];
        }
        else {
            $type = 0;
        }

        if (isset($_GET["other"])) {
            $other = $_GET["other"];
        }
        else {
            $other = 0;
        }
        ?>


        <input type="text"  name="name" value="<?php echo $name; ?>">
        <input type="text"  name="type"  value="<?php echo $type; ?>">
        <input type="text"  name="other" value="<?php echo $other; ?>">

I have tried to also do

        <?php
            $name = $_GET["name"] ?: 0;
        ?>

This puts in a value of 0 into my form but I get the error Notice: Undefined index: name

  • 写回答

3条回答 默认 最新

  • doulin2025 2014-04-26 11:33
    关注

    Use isset() in the ternary operator:

    $name = isset($_GET["name"]) ? $_GET["name"] : 0;
    

    You get the notice because you evaluate $_GET['name'] directly, without using isset() or empty() wrapper.

    You might prefer to make a resuble function to simply your code:

    function filterThing($key){
        return isset($_GET[$key]) ? $_GET[$key] : 0;
    }
    
    $name = filterThing('name');
    $type = filterThing('type');
    $other = filterThing('other');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧