以下功能让我抓狂。 100x 到底如何等于 100,然后 100x 被报告为整数?
对于我的一生,我无法弄清楚。
您可以复制并粘贴整个内容并亲自查看。
我在这里遗漏了一个简单的点,请帮助我。
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>";
}
上面的代码,运行时返回以下内容;
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!
我可以通过添加以下位来解决这种情况
if (!is_numeric($val))
{
return false;
}
立即到 blp_int 函数的顶部,但是,..我仍然非常好奇为什么 php 认为 100x=100 是相等的。
最佳答案
正如您在 this example 中看到的那样,将 100x
转换为整数会将其转换为 100
。由于您没有使用严格比较,因此 '100x' == 100
为 true。 PHP 从中删除了 x
,仅生成 100
。
您可以使用严格比较(也比较类型),这样 '100x' === 100
将返回 false。使用它,任何时候将字符串与整数进行比较,都会返回 false。
根据您的编辑: is_numeric
可能不是最可靠的,因为它对于字符串格式的数字返回 true,例如 '100'
。如果您希望数字为整数(而不是字符串),则可以使用is_integer
。我不太确定你到底在做什么,但我想我应该添加此注释。
关于php - 无法确定字符串当前是否为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505466/