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

回眸只為那壹抹淺笑 提交于 2019-12-03 17:12:50

问题


My understanding is...

if is_numeric($input) === true

then either

is_float($input) === true OR

is_int($input) === true OR

$input === 0 OR

$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?


回答1:


See PHP's documentation on is_numeric. It talks about everything that is allowed, and it's more than is_float and 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.


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 has two different modes for converting to int; this answer explains it a bit more.

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.




回答2:


See the docs. A numeric value can be:

  • An integer
  • A float
  • Exponential
  • A positive Hexadecimal
  • A string containing most of these


来源:https://stackoverflow.com/questions/8307104/is-numeric-vs-is-float-vs-is-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!