Current Location: Home> Latest Articles> How to solve the problem of is_nan in PHP to determine Infinity and NaN

How to solve the problem of is_nan in PHP to determine Infinity and NaN

gitbox 2025-05-28

In PHP, the is_nan function is used to detect whether a variable is "NaN" (Not a Number). Although this function can effectively judge most non-numeric exceptions, it confuses developers when dealing with special numeric values, such as Infinity .

What are NaN and Infinity?

  • NaN (Not a Number) : indicates a special value that is not a number. It usually occurs when the calculation result cannot be defined as a numeric value, such as 0/0 or a negative square root number.

  • Infinity : Indicates a very large value that usually occurs when it exceeds the maximum floating value supported by PHP. For example, when calculating 1/0, you will get INF (positive infinite) or -INF (negative infinite).

Why is_nan cannot correctly judge Infinity?

In PHP, the is_nan function only determines whether a value is NaN , and it will not determine whether it is Infinity . For example:

 var_dump(is_nan(NAN)); // bool(true)
var_dump(is_nan(INF)); // bool(false)
var_dump(is_nan(-INF)); // bool(false)

As you can see, is_nan returns true only when the value is NaN , other such as INF or -INF return false , which may confuse developers because both INF and NaN represent the exception's numerical state.

How to solve this problem?

In order to handle the judgment of Infinity and NaN , we can solve this problem by combining other functions. There is an is_infinite function in PHP that can be used to determine whether a value is infinite (positive or negative infinite), while is_nan is used to determine whether it is "NaN".

Solution:

 <?php

function is_nan_or_infinite($value) {
    if (is_nan($value)) {
        return 'NaN';
    } elseif (is_infinite($value)) {
        return 'Infinity';
    } else {
        return 'Neither NaN nor Infinity';
    }
}

echo is_nan_or_infinite(NAN); // Output NaN
echo is_nan_or_infinite(INF); // Output Infinity
echo is_nan_or_infinite(-INF); // Output Infinity
echo is_nan_or_infinite(123); // Output Neither NaN nor Infinity

?>

This custom function is_nan_or_infinite judges two special values ​​NaN and Infinity . By first using is_nan and then using is_infinite to judge, the two can be accurately distinguished.

Things to note in practical application

  • NaN usually occurs when mathematical calculation errors, operations such as 0/0 or sqrt(-1) will return NaN . Therefore, if you encounter these outliers in data processing, you should deal with them in time to avoid affecting the results.

  • Infinity usually occurs when mathematical overflow, like 1/0 or very large numerical calculations return INF or -INF . In applications, Infinity may affect the normal flow of data, so it needs to be handled reasonably according to business needs.