Integer Division

PHP 7 has a new function intdiv() that performs integer division. While the regular division operator / returns a floating point number (which then can be cast to integer), intdiv() directly returns an integer:

var_dump(5 / 2);
var_dump((int) (5 / 2));
var_dump(intdiv(5, 2));

Running this program will produce the following output:


There are some edge cases that yield special results. First, we still cannot divide by zero:

var_dump(intdiv(1, 0));

Thanks to the new error handling in PHP, this will raise an error exception, which, when not caught, will turn into a fatal error. We cover these changes in greater detail in the “Error Handling” chapter.

PHP Fatal error:  Uncaught DivisionByZeroError:
Division by zero in ...

The main difference between using the regular division operator and intdiv() becomes obvious when the result of an integer division cannot be represented as an integer anymore. Instead of losing precision, because the intermediate result is represented as a floating point number and then converted to an integer, intdiv() will fail. Let us try this out by working with the smallest and largest integer that a 64-bit system can represent:


At first glance, it seems that more negative numbers can be represented than positive numbers:


However, if you acknowledge that zero is also a number, and zero is non-negative, things even out. But what about trying to divide PHP_INT_MIN and PHP_INT_MAX by -1?

var_dump(intdiv(PHP_INT_MAX, -1));
var_dump(intdiv(PHP_INT_MIN, -1));

Technically, dividing by -1 means switching the sign. This works fine for PHP_INT_MAX, but fails for PHP_INT_MIN:

PHP Fatal error:  Uncaught ArithmeticError:
Division of PHP_INT_MIN by -1 is not an integer in ...