is_numeric() 与 is_float() 与 is_int() [英] is_numeric() vs. is_float() vs. is_int()
问题描述
我的理解是...
if is_numeric($input) === true
然后要么
is_float($input) === true
或
is_int($input) === true
或
$input === 0
或
$input
是一个数字字符串(意味着如果它没有用引号括起来,它将满足前 3 个之一).
$input
is a numeric string (meaning it'd satisfy one of the first 3 if it weren't wrapped in quotes).
准确吗?还有其他区别吗?
Is that accurate? Are there other differences?
推荐答案
查看 PHP 关于 is_numeric.它讨论了允许的所有内容,而且不仅仅是 is_float
和 is_int
.
See PHP's documentation on is_numeric. It talks about everything that is allowed, and it's more than is_float
and is_int
.
同样重要的是要注意 is_int
仅适用于整数类型的事物,这意味着不允许使用字符串表示.这是验证表单输入是否为整数时的常见问题.您应该将 filter_var
或过滤器系列中的某些内容与过滤器 FILTER_VALIDATE_INT
一起使用.对于浮点数,请使用 FILTER_VALIDATE_FLOAT
.
It's also important to note that is_int
only works on things that are type integer, meaning string representations are not allowed. This is a common problem when verifying that form input is an integer. You should use filter_var
or something from the filter family with the filter FILTER_VALIDATE_INT
. For floats, use FILTER_VALIDATE_FLOAT
.
此外,如果您尝试检查整数的原因是将参数验证为整数,那么在 PHP 7 中您可以这样做:
Also, if the reason you are trying to check for an integer is to validate a parameter as being an int, then in PHP 7 you can do this:
function foo(int $i) {
// $i is guaranteed to be an int (is_int) will be true
}
PHP 7 有两种不同的转换为 int 的模式;这个答案对其进行了更多解释.
PHP 7 has two different modes for converting to int; this answer explains it a bit more.
请注意,如果您正在验证表单元素的内容,这可能不是您想要的.使用 filter_var
解决方案.
Note that this is probably not what you want if you are validating the contents of a form element. Use the filter_var
solution for that.
这篇关于is_numeric() 与 is_float() 与 is_int()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!