PHP Reference ยท Math Functions
PHP is_nan() and is_infinite() functions
Reference for PHP is_nan(), is_infinite() and is_finite(): detect NAN and INF float results, why NAN never equals itself, fdiv() and division by zero.
Floating-point arithmetic has two kinds of special values besides ordinary numbers: infinity (INF and -INF), produced by overflow or by fdiv(1, 0), and NAN ("not a number"), produced by operations with no sensible answer, such as sqrt(-1) or INF - INF. PHP offers three checks: is_nan(), is_infinite() and is_finite().
The checks are necessary because NAN is not equal to anything, not even itself: NAN == NAN is false. So $x === NAN can never detect it.
<?php var_dump(is_nan(sqrt(-1))); // bool(true) var_dump(is_infinite(exp(1000)));// bool(true) var_dump(NAN == NAN); // bool(false)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
is_nan(float $num): bool is_infinite(float $num): bool is_finite(float $num): bool
| Name | Description |
|---|---|
$num |
The value to test. Integers and numeric strings are converted to float. |
Return value: true or false. is_nan() is true only for NAN. is_infinite() is true for INF and -INF. is_finite() is true for every ordinary number, and false for NAN and both infinities.
Errors: a TypeError for non-numeric strings and arrays.
Usage notes
- Never compare with
NAN. Useis_nan().in_array(NAN, ...)andarray_search(NAN, ...)do not find it either. is_finite()is the safest single guard for calculation results: it rejects both NAN and infinity.- Integers are always finite, so these functions return
false,false,truefor ints. - Division by zero throws.
1 / 0,1 % 0andintdiv(1, 0)raiseDivisionByZeroError. Usefdiv()(PHP 8.0+) when you wantINForNANinstead. - Printing:
echo INFprintsINF,-INFprints-INF,NANprintsNAN. - JSON can't carry them:
json_encode()fails on NAN and INF. Replace or null them out before encoding. - Casting:
(int) NANand(int) INFgive0and, in PHP 8.5, raise a warning that the float is not representable as an int. Check withis_finite()first.