dongxuan2015 2012-02-29 19:34
浏览 24
已采纳

无法确定字符串当前是否为整数

The following funciton drove me nuts. How on earth 100x could be equal to 100 and then 100x is reported as an integer?
For the life of me, I cannot figure it out. You can copy and paste the whole thing and see it for yourself.
I'm missing a simple point somewhere here, help me out guys.

function blp_int($val) {
    $orgval = $val;
    $num = (int)$val;    
    echo "<li><font color=red>val: ". $val . " is being checked to see if it's an integer or not";
    echo "<li><font color=red>orgval: ". $orgval ;
    echo "<li><font color=red>num: ". $num ;
    if ($orgval==$num) {
        echo "<li><font color=red><b>YES IT IS! the [{$orgval}] is equal to [{$num}]</b>";
        return true;
    }
    return false;
}

if (blp_int("100"))
{
    echo "<h1>100 is an integer!</h1>";
}
else
{
    echo "<h1>100 is NOT an integer!</h1>";
}

if (blp_int("100x"))
{
    echo "<h1>100x is an integer!</h1>";
}
else
{
    echo "<h1>100x is NOT an integer!</h1>";
}

the above code, when run returns the following;

val: 100 is being checked to see if it's an integer or not
orgval: 100
num: 100
YES IT IS. the [100] is equal to [100]
100 is an integer!

val: 100x is being checked to see if it's an integer or not
orgval: 100x
num: 100
YES IT IS. the [100x] is equal to [100]
100x is an integer!

I can remedy the situation by adding the following bits

    if (!is_numeric($val))
    {
        return false;
    }

to the top of the blp_int function right off the bat but,.. I'm still super curious to find out why on earth php thinks 100x=100 are equals.

  • 写回答

4条回答 默认 最新

  • doumengmian1180 2012-02-29 19:38
    关注

    As you can see in this example, casting 100x as an integer converts it to 100. Since you are not using strict comparison, '100x' == 100 is true. PHP removes the x from it to make just 100.

    You could use strict comparison (which also compares the types), such that '100x' === 100 would return false. Using it, any time a string was compared to an integer, it would return false.


    As per your edit: is_numeric may not be the most reliable, as it will return true for numbers formatted as a string, such as '100'. If you want the number to be an integer (and never a string), you could use is_integer instead. I'm not quite sure what exactly you're doing, but i thought I'd add this note.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?