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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么