Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP is_nan() Function
The is_nan() function in PHP checks whether a given value is NaN (Not a Number). This is particularly useful when working with mathematical operations that might produce invalid results.
Syntax
is_nan ( float $val ) : bool
Parameters
| Parameter | Description |
|---|---|
| val | The floating-point value to check for NaN |
Return Value
Returns true if the value is NaN, false otherwise.
Example
The following example demonstrates how is_nan() works with various mathematical operations that produce NaN ?
<?php // Operations that produce NaN $val1 = sqrt(-1); // Square root of negative number $val2 = acos(2); // Arc cosine of value > 1 $val3 = log(-5); // Logarithm of negative number // Test each value echo "sqrt(-1): "; var_dump($val1); echo "is_nan result: " . (is_nan($val1) ? 'true' : 'false') . "<br><br>"; echo "acos(2): "; var_dump($val2); echo "is_nan result: " . (is_nan($val2) ? 'true' : 'false') . "<br><br>"; echo "log(-5): "; var_dump($val3); echo "is_nan result: " . (is_nan($val3) ? 'true' : 'false') . "<br><br>"; // Valid number $val4 = sqrt(25); echo "sqrt(25): "; var_dump($val4); echo "is_nan result: " . (is_nan($val4) ? 'true' : 'false'); ?>
The output of the above code is ?
sqrt(-1): float(NAN) is_nan result: true acos(2): float(NAN) is_nan result: true log(-5): float(NAN) is_nan result: true sqrt(25): float(5) is_nan result: false
Key Points
Important considerations when using is_nan():
- NaN values are created by invalid mathematical operations
- NaN is not equal to any value, including itself
- Available in PHP 4.x, 5.x, 7.x, and 8.x
- Accepts only float values as parameter
Conclusion
The is_nan() function is essential for validating mathematical calculations in PHP. Use it to detect invalid results from operations like square roots of negative numbers or logarithms of non-positive values.
Advertisements
