drau89457 2014-03-14 08: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 09: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部