doumei9589 2017-12-18 18:05
浏览 24
已采纳

使用比较运算符是否始终与ctype_digit()或is_numeric()相同?

For a variable like the following $p = $_GET['page']

In conditions like the following

if ($p > 0)
if ($p < 0)
if ($p >= 0)
if ($p <= 0)
if ($p == 0)

does it work same as

if (ctype_digit($p)){//Logic}
//or...
if (is_numeric($p)){//Logic}
  • 写回答

1条回答 默认 最新

  • douzouchang7448 2017-12-18 18:26
    关注

    My suggestion is pass in the right datatype for the job. So if you need number pass that to this code.

    If you cannot control what is being passed in then check what it is first. This makes you take a second look when code starts to break. I would use is_numeric because it know negatives and floats unlike ctype_digit

    is_numeric("-10"); //TRUE 
    ctype_digit("-10"); //FALSE
    is_numeric("12.10"); //TRUE 
    ctype_digit("12.10"); //FALSE
    

    So in the end you would want to do something like:

    $p = $_GET['page'];
    
    if(is_numeric($p)){
        $p = (int)$p;
        //Do stuff with an int
    } else {
        //Not sure what should happen here...
    }
    

    PHP is super flexible with casting for us but when it comes to trying to find a bug in your code it becomes hard to find when you act like everything is coming in good ie if($p>0){} seems like you know you have a number and I would keep looking elsewhere.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号