php is_numeric() 与 is_float() 与 is_int()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8307104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is_numeric() vs. is_float() vs. is_int()
提问by ryanve
My understanding is...
我的理解是...
if is_numeric($input) === true
如果 is_numeric($input) === true
then either
那么要么
is_float($input) === true
OR
is_float($input) === true
或者
is_int($input) === true
OR
is_int($input) === true
或者
$input === 0
OR
$input === 0
或者
$input
is a numeric string (meaning it'd satisfy one of the first 3 if it weren't wrapped in quotes).
$input
是一个数字字符串(意味着如果它没有用引号括起来,它将满足前 3 个之一)。
Is that accurate? Are there other differences?
那是准确的吗?还有其他区别吗?
回答by Levi Morrison
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_numeric 的PHP 文档。它讨论了允许的所有内容,而且不仅仅是is_float
和is_int
。
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
.
同样重要的是要注意,is_int
仅适用于整数类型的事物,这意味着不允许使用字符串表示。这是验证表单输入是否为整数时的常见问题。您应该filter_var
将过滤器系列中的或某些东西与过滤器一起使用FILTER_VALIDATE_INT
。对于浮点数,请使用FILTER_VALIDATE_FLOAT
.
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:
此外,如果您尝试检查整数的原因是将参数验证为 int,那么在 PHP 7 中您可以这样做:
function foo(int $i) {
// $i is guaranteed to be an int (is_int) will be true
}
PHP 7 has two different modes for converting to int; this answerexplains it a bit more.
PHP 7 有两种不同的转换为 int 的模式;这个答案解释了更多。
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.
请注意,如果您正在验证表单元素的内容,这可能不是您想要的。filter_var
为此使用解决方案。