PHP - is_numeric() 的使用是必要的,还是可以使用比较符号来处理所有正数的情况?

标签 php math evaluation numeric isnumeric

好像比较简单的标志>,>=它们的反向分量可以评估某个变量是否为数字。示例 $whatami='beast'; ($whatami<0)?echo 'NaN':echo 'is numeric!';

有没有is_numeric() 正值(数字 >0) 是否需要使用?似乎使用上面的比较符号可以确定变量是否为数字..

最佳答案

正如我发现的那样,许多辅助函数确实是必需的,因为 PHP 不是强类型的。我发布了 similar question (虽然不是相似)关于本周早些时候的 isset。需要注意的一件事是,PHP 会将您的字符串更改为其整数值,以便在某些情况下(当存在混合类型时)进行比较。这一点不容忽视。我认为这是 is_numeric

的有力案例

来自 PHP Manual

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

要考虑的另一件事是 PHP 中的“什么是 0”。那意义重大。它并不总是数字。它可能是数字字符串、 bool 值 false、整数等...这就是存在这些辅助函数的原因。

添加到我的答案中:

改变你的例子:

$whatami='beast';  
($whatami<5) ? echo 'less than 5' : echo 'more than 5';

PHP 会将“beast”更改为其等效的整数,然后进行比较。这会产生意想不到的结果。如果您真的想要类似的东西,则必须将其包装在另一个条件中:

$whatami='beauty';  
if(is_numeric($whatami){
    ($whatami<5) ? echo 'less than 5' : echo 'more than 5';
} else {
    exit('what, am I not pretty enough for a beast?');
}

然后你会得到你想要的结果(尽管它可能很奇怪)。

关于PHP - is_numeric() 的使用是必要的,还是可以使用比较符号来处理所有正数的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315264/

相关文章:

php - 为 Codeigniter 中的 foreach() 提供的参数无效

php - 将数组附加到多维数组,保留键

php - 仅允许注册用户从我的 Amazon S3 存储桶中下载

python kwargs 表达式评估

python - 在 python : ranked list vs. 中评估搜索查询的结果,一个手动标记为正确的文档

java - PHP Java AES CBC加密不同结果

algorithm - "K-transformed"排列

math - 合并旋转轴向量

php - 以百分比计算值范围

algorithm - 表达式评估