nan() throws a warning for strings

I've been using the is_nan() function (ie is-not-a-number) to check whether a variable taken from the query string is a number or not. However, in the case of the variable being a string (in which case is_nan() should return TRUE ), the function also throws the following rather annoying warning:

Warning: is_nan() expects parameter 1 to be double, string given

Since is_nan() is for checking if a variable is not a number, why would it throw an error for a string? I would have thought that it should accept non-numerical parameters, since that is kind-of it's purpose...

Is there a reason why such a warning would be thrown? Is there some sense that I'm not seeing here?

Note: When the error is thrown, the function still behaves as expected - it returns TRUE for strings and FALSE for numbers. However, I am wondering why it would also throw a warning in the case of a string.
I have also since started using is_int() because I have found it to be better suited to my purposes, and so I am not looking for alternatives. I am just curious about this behaviour.


The function is intended for checking the validity of return values of mathematical functions and operations (see NaN@wikipedia) and expects a float as a parameter. Example taken from the function's documentation:

$nan = acos(8);
var_dump($nan, is_nan($nan));

# prints:
float(NAN)
bool(true)

What you probably want is is_numeric() :

if (!is_numeric($arbitraryType)) {

From here :

nan/"not a number" is not meant to see if the data type is numeric/textual/etc..

NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.

The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part. There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.


A look at the documentation suggests that your understanding of is_nan() is incorrect. I think you need to use is_int() or is_float() . Alternatively you could use an explict cast to convert your variable.

is_nan() is a maths function while is_int() is a variable handling function.

链接地址: http://www.djcxy.com/p/26614.html

上一篇: 如何将错误和警告记录到文件中?

下一篇: nan()会为字符串发出警告