drau89457 2014-03-14 16:59
浏览 56
已采纳

PHP嵌套if语句 - 有更好的方法吗?

Could I nest these PHP IFs in a better to understand/ more logical way?

 if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
    {
        $numwelds = $_GET['numberofwelds'];
        $numconwelds = $_GET['numberofconwelds'];

        if (is_int($numwelds) && is_int($numconwelds))
        {
            $total = $numwelds + $numconwelds;
            $response = json_encode($total);
            header(“Content-Type:application/json”);  
            echo $response;
            exit;
        }
    }
  • 写回答

4条回答 默认 最新

  • dtr84664 2014-03-14 17:02
    关注

    You can use ternary statements to make this a little bit nicer. The logic is the same, but you can reduce the number of lines required, at the expense of a little readability.

    Some other important points to note:

    • You had smart quotes. is not the same as ". The former will not be parsed by PHP -- and will most likely throw an Internal Server Error.

    • Don't use is_int() — it will lie to you. When you're working with user input data, you'll be fetching it from $_POST, $_GET superglobal arrays. All those values will be stored as strings. is_int() treats a string containing a number, for e.g., "42" as as a string, and will return false. Use is_numeric() instead.

    Updated code:

    $numwelds = isset($_GET['numberofwelds']) ? $_GET['numberofwelds'] : '';
    $numconwelds = isset($_GET['numberofconwelds']) ? $_GET['numberofconwelds'] : '';
    
    if (is_numeric($numwelds) && is_numeric($numconwelds))
    {
        $total = $numwelds + $numconwelds;
        $response = json_encode($total);
        header("Content-Type: application/json");  
        echo $response;
        exit;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度