Search code examples
phpwarningssuppress-warnings

PHP function is_nan() throws a warning for strings


I've been using the is_nan() function (i.e. 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.


Solution

  • 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)) {