Division Operator Throws Exception When Dividing Number by Zero in PHP 8.0

Division Operator Throws Exception When Dividing Number by Zero in PHP 8.0

The division operator (/) is an arithmetic operator that allows to divide one number by another. This operator returns a floating-point number, unless both operands are integers. In this case, an integer is returned.

In all PHP 7 versions, the division operator has inconsistent behavior when dividing a number by zero. The modulo operator (%) throws a DivisionByZeroError when modulo by zero is performed:

<?php

echo 1 % 0;

Example will output:

Fatal error: Uncaught DivisionByZeroError: Modulo by zero in main.php:3

However, the division operator emits a warning and returns +INF, -INF or NAN.

<?php

echo 1 / 0;

In PHP 7 example will output:

Warning: Division by zero in main.php on line 3
INF

Since PHP 8.0, the division operator throws an exception when dividing a number by zero.

<?php

echo 1 / 0;

If we run this code snippet in PHP 8.0 or newer versions, we will get a DivisionByZeroError:

Fatal error: Uncaught DivisionByZeroError: Division by zero in main.php:3

Leave a Comment

Cancel reply

Your email address will not be published.