PHP function is_nan () throws warning for strings

I used the is_nan() function (i.e. is-not-a-number) to check if a variable taken from the query string is a number or not. However, if the variable is a string (in this case is_nan() should return TRUE ), the function also generates the following rather annoying warning:

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

Since is_nan() designed to check if a variable is not a number, why did it throw an error for the string? I would think that it should accept non-numeric parameters, since this is kind of a goal ...

Is there a reason why such a warning would be thrown? Does it make sense that I do not see here?

Note. If an error occurs, the function still behaves as expected - it returns TRUE for strings and FALSE for numbers. However, I wonder why it also issued a warning in case of a string.
Since then, I started using is_int() because I found that it is better suited for my purposes, and therefore I am not looking for an alternative. I'm just curious about this behavior.

+4
source share
6 answers

The function is designed to verify the correctness of the return values ​​of mathematical functions and operations (see NaN @wikipedia ) and expects the float as a parameter. Example taken from the documentation :

 $nan = acos(8); var_dump($nan, is_nan($nan)); # prints: float(NAN) bool(true) 

What you possibly want is is_numeric() :

 if (!is_numeric($arbitraryType)) { 
+13
source

From here :

nan / "not a number" is not intended to be viewed if the data type is digital / text / etc ..

NaN is actually a set of values ​​that variables can be stored in a floating point, but do not actually evaluate to the correct 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 for managing combinations of values ​​that can be placed in 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.

+4
source

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 can use explication to transform your variable.

is_nan() is a mathematical function, and is_int() is a variable processing function.

+2
source

Because in this situation, he must perform an implicit throw. He must warn you. I want to know where implicit throws occur. It is too error prone.

+1
source

Check: http://se2.php.net/manual/en/function.is-nan.php

"bool is_nan (float $ val)" <- That's why.

0
source

You get an error if you end the is_nan () function in a conditional expression, for example:

 if(is_nan('xxx')) { echo "Hey, that no number!"; } else { ............... } 
-2
source

All Articles