PHP is_nan() function


The is_nan() function in PHP checks whether a given value is "NaN" (Not a Number). NaN is a special floating-point value that represents an undefined or unrepresentable value, particularly in floating-point calculations. For example, the result of dividing 0 by 0 is considered NaN.

Syntax:

is_nan(mixed $value): bool
  • $value: The value to be checked.
  • Return Value: Returns true if the value is NaN; otherwise, it returns false.

Example 1: Checking NaN with a Calculation

<?php $result = 0 / 0; // This will be NaN if (is_nan($result)) { echo "The result is NaN."; } else { echo "The result is a number."; } ?>

Output:

The result is NaN.

Explanation: In this example, dividing 0 by 0 results in NaN, which is_nan() detects.

Example 2: Checking a Valid Number

<?php $number = 5.5; if (is_nan($number)) { echo "The number is NaN."; } else { echo "The number is valid."; } ?>

Output:

The number is valid.

Explanation: Since 5.5 is a valid number, is_nan() returns false.

Example 3: Checking NaN with Invalid Operations

<?php $invalidOperation = sqrt(-1); // This will be NaN in most cases if (is_nan($invalidOperation)) { echo "The result is NaN."; } else { echo "The result is a number."; } ?>

Output:

The result is NaN.

Explanation: The square root of -1 is NaN, which is_nan() identifies.

Example 4: Checking Different Data Types

<?php $values = [NaN, 10, "string", null]; foreach ($values as $value) { if (is_nan($value)) { echo "$value is NaN.\n"; } else { echo "$value is not NaN.\n"; } } ?>

Output:

NAN is NaN. 10 is not NaN. string is not NaN. is not NaN.

Explanation: This loop checks various values, identifying which one is NaN. Note that NaN is often represented as NAN in output.

Key Points:

  • Use Cases: is_nan() is useful for validating calculations that can result in undefined values, such as division by zero or operations involving negative square roots.
  • Type Checking: The function is specifically designed for floating-point numbers, and it will return false for integers, strings, and other data types.
  • NaN Representation: In PHP, NaN is represented as a special floating-point value, and you can create it using NAN.

Example of NaN Creation:

<?php $nanValue = NAN; // Assigning NaN directly if (is_nan($nanValue)) { echo "This value is NaN."; } ?>

Output:

This value is NaN.

Explanation: Here, NAN is assigned to a variable, and is_nan() confirms it is indeed NaN.

In summary, is_nan() is a handy function in PHP for checking whether a value is NaN, allowing developers to handle potential errors or undefined behaviors in numerical calculations effectively.