Current Location: Home> Latest Articles> How to use the is_nan function of PHP to determine whether a value is NaN?

How to use the is_nan function of PHP to determine whether a value is NaN?

gitbox 2025-05-28

In PHP, the is_nan function is used to check whether a value is "NaN" (Not-a-Number). NaN is a special value representing an illegal number, which usually occurs during numerical calculations, especially when performing invalid mathematical operations, such as 0 divided by 0, or when converting non-numeric strings into numbers.

The is_nan function takes a parameter and returns a boolean value: true if the passed value is NaN, otherwise false .

grammar

 is_nan($var);

parameter

  • $var : The value to be checked.

Return value

  • Return true if $var is NaN;

  • If $var is not NaN, false is returned.

Sample code

Here are some examples showing how to use the is_nan function to determine whether a value is NaN.

Example 1: Check if a value is NaN

 <?php
$val = 0 / 0; // produce NaN
if (is_nan($val)) {
    echo "The value is NaN";
} else {
    echo "The value is not NaN";
}
?>

In the example above, the result of 0/0 is NaN, so the is_nan function will return true and output "value is NaN".

Example 2: Check if the string is converted to a number is NaN

 <?php
$str = "abc"; // Cannot convert to a valid number
$val = (float) $str; // Casting to floating point number
if (is_nan($val)) {
    echo "The value is NaN";
} else {
    echo "The value is not NaN";
}
?>

In this example, the string "abc" cannot be converted to a valid number, so it will become NaN after conversion, and is_nan will return true .

Example 3: Check if other mathematical calculations produce NaN

 <?php
$result = sqrt(-1); // The square root of the negative number is NaN
if (is_nan($result)) {
    echo "The calculation result is NaN";
} else {
    echo "The calculation result is not NaN";
}
?>

sqrt(-1) returns NaN because the square root of the negative number is invalid within the real range. Therefore is_nan will return true and output "the result of calculation is NaN".

Things to note

  1. The difference between NaN and NULL and INF :

    • NaN means "not a number", it is different from NULL and positive and negative infinite ( INF ). NULL is a null value, and INF is an infinitely large or infinitely small number. It is NaN, not NULL or INF, which is used to judge .

  2. NaN and self-equality :

    • NaN has a special property, which is not equal to any value (including itself). So you can't use == or == to determine whether a value is NaN. It must be checked using is_nan .

in conclusion

PHP's is_nan function is an important tool to determine whether a value is NaN, especially when it comes to mathematical calculations. Through this function, we can effectively capture and handle illegal numerical calculations.