Current Location: Home> Latest Articles> PHP 8's fdiv() Function Explained: Floating-Point Division and Exception Handling

PHP 8's fdiv() Function Explained: Floating-Point Division and Exception Handling

M66 2025-06-20

PHP 8's fdiv() Function: Floating-Point Division and Exception Handling

In PHP 8, the fdiv() function provides a method for performing floating-point division that conforms to the IEEE 754 standard. This function divides two numbers and returns a floating-point value, allowing for special cases such as division by zero to be handled automatically, returning specific mathematical results.

How the fdiv() Function Works

The fdiv() function is similar to other mathematical functions in PHP, such as intdiv() and fmod(), but with one key difference: it can handle division by zero. Specifically, fdiv() will return different values depending on the case of division by zero:

  • INF (Infinity) - Represents a result of positive infinity.
  • -INF (Negative Infinity) - Represents a result of negative infinity.
  • NAN (Not a Number) - Returned when the result is undefined, typically when the operands cannot be meaningfully computed.

Example 1: Basic Usage


<?php
echo fdiv(15, 4);
?>
    

Output


3.75
    

Example 2: Handling Division by Zero


<?php
echo fdiv(10, 0); // INF (Positive Infinite)
echo fdiv(-10, 0); // -INF (Negative Infinite)
echo fdiv(0, 0);  // NAN (Not a number)
?>
    

Output


INF -INF NAN
    

Conclusion

The fdiv() function in PHP 8 provides a robust method for floating-point division, adhering to the IEEE 754 standard. This function not only performs regular floating-point operations but also gracefully handles division by zero, returning the mathematically defined results of infinity, negative infinity, or not a number. This feature offers greater flexibility for high-precision mathematical calculations in PHP.