Skip to content
Tutorials Center
My learning

Topics

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
<?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

PHP Producing and detecting special values

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.

PHP Dividing by zero and guarding results

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

PHP
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. Use is_nan(). in_array(NAN, ...) and array_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, true for ints.
  • Division by zero throws. 1 / 0, 1 % 0 and intdiv(1, 0) raise DivisionByZeroError. Use fdiv() (PHP 8.0+) when you want INF or NAN instead.
  • Printing: echo INF prints INF, -INF prints -INF, NAN prints NAN.
  • JSON can't carry them: json_encode() fails on NAN and INF. Replace or null them out before encoding.
  • Casting: (int) NAN and (int) INF give 0 and, in PHP 8.5, raise a warning that the float is not representable as an int. Check with is_finite() first.