Open In App

PHP is_finite(), is_infinite(), is_nan() Functions

Given any numerical value, it can be classified into 3 different classes such as Finite Number, Infinite Number, and Not a Number or commonly known as NaN. While developing a project that is highly dependent on User Inputs there might be many cases where the user provides inappropriate inputs while a function expects a finite numerical input thus creating an unhandled situation or unexpected result.

Thus it is a secure option to check whether a given input value is finite or not.



 



is_finite() Function

Syntax:

bool is_finite ($value)

Parameters: The function takes a single parameter which is a float that is to be checked.

Return Type: This function returns TRUE if the given value is finite otherwise returns FALSE.

Examples:

Input :  $value = M_PI_4;
Output : TRUE

Input : $value = log(0);
Output : FALSE        

is_infinite() Function

Syntax:

bool is_infinite ($value)

Parameters: The function takes a single parameter which is a float that is to be checked.

Return Type: This function returns TRUE if the given value is infinite otherwise returns FALSE.

Examples:

Input :  $value = M_PI_4;
Output : FALSE

Input : $value = log(0);
Output : TRUE        

is_nan() Function

Syntax:

bool is_nan ($value)

Parameters: The function takes a single parameter which is a float that is to be checked.

Return Type: This function returns TRUE if the given value is not a number otherwise returns FALSE.

Examples:

Input :  $value = M_PI_4;
Output : FALSE

// cos function can not be greater than 1
Input : $value = acos(1.1); 
Output : TRUE        

Below program illustrates the working of is_finite(), is_infinite(), is_nan() functions in PHP:




<?php
  
// PHP code to illustrate the working of 
// is_finite(), is_infinte() and is_nan() 
// Functions 
  
// Finite Value: PI
$val1 = M_PI; 
  
// In-built value of INFINITY
$val2 = INF; 
  
// Produces NaN as COS value can reside 
// between -1 to +1 both inclusive
$val3 = acos(-1.01); 
  
echo var_dump(is_finite($val1), 
    is_finite($val2), is_finite($val3)) . "\n";
  
echo var_dump(is_infinite($val1), 
    is_infinite($val2), is_infinite($val3)) . "\n";
  
echo var_dump(is_nan($val1), 
    is_nan($val2), is_nan($val3)) . "\n";
                          
?>

Output:

bool(true) bool(false) bool(false) 
bool(false) bool(true) bool(false) 
bool(false) bool(false) bool(true) 

Note:


Article Tags :