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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:23:10  来源:igfitidea点击:

is_numeric() vs. is_float() vs. is_int()

phptypesnumbers

提问by ryanve

My understanding is...

我的理解是...

if is_numeric($input) === true

如果 is_numeric($input) === true

then either

那么要么

is_float($input) === trueOR

is_float($input) === true或者

is_int($input) === trueOR

is_int($input) === true或者

$input === 0OR

$input === 0或者

$inputis 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_floatand is_int.

请参阅有关is_numeric 的PHP 文档。它讨论了允许的所有内容,而且不仅仅是is_floatis_int



It's also important to note that is_intonly 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_varor 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_varsolution for that.

请注意,如果您正在验证表单元素的内容,这可能不是您想要的。filter_var为此使用解决方案。

回答by fncomp

See the docs. A numeric value can be:

请参阅文档。数值可以是:

  • An integer
  • A float
  • Exponential
  • A positive Hexadecimal
  • A string containing most of these
  • 一个整数
  • 一个浮标
  • 指数
  • 一个正十六进制
  • 包含其中大部分内容的字符串