PHP 8.0: New fdiv function

Version8.0
TypeNew Feature

PHP 8 adds a new fdiv() function to fit along functions such as fmod() and intdiv().

As of now, attempting a divide a number by zero results in inconsistent behavior.

Division operator triggers warnings

$num = 1 / 0;
// Warning: Division by zero in ... on line ...

intdiv() function throws DivisionByZeroError exceptions

$num = intdiv(1, 0);
// Fatal error: Uncaught DivisionByZeroError: Division by zero in ...:...

Modulo operator throws DivisionByZeroError exceptions

$mod = 1 % 0;
// Fatal error: Uncaught DivisionByZeroError: Modulo by zero in ...:...

Semantically, the division operator should throw a DivisionByZeroError exception as well, but due to backwards compatibility issues, it is still a warning.


In an attempt to streamline this, Nikita suggested to add the new fdiv() function.

This function will follow the IEEE-754 standard on Floating-Point Arithmetic, and return NAN, or ±INF as float. The return value of fdiv will be identical to the current division operator's behavior.


## +INF
fdiv(1, 0); // float(INF)

$num = 1 / 0; // float(INF)
// Warning: Division by zero in ... on line ...

## -INF
fdiv(-1, 0); // float(-INF)

$num = -1 / 0; // float(-INF)
// Warning: Division by zero in ... on line ...

The division operator will eventually throw DivisionByZeroError when this function is well-established in the future.

Polyfill

A PHP 7.0+ polyfill that mimics the new fdiv() function:

if (!function_exists('fdiv')) {
    function fdiv(float $dividend, float $divisor): float {
        return @($dividend / $divisor);
    }
}

Backwards compatibility impact

fdiv() is a new function. A quick GitHub search did not reveal any positive results for existing code that declares a function with the same name.

It is recommended that you use this function whenever possible (see the polyfill above) because division by zero using division operator is already triggering a PHP warning in your existing code, which will escalate to a DivisionByZeroError exception in the future.


Externals.io discussion Implementation