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

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 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数