# Integer Division

> Section in “New and Extended Functionality › Mathematics” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/mathematics/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:

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

Running this program will produce the following output:

    double(2.5)
    int(2)
    int(2)

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

``` php
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](https://php7explained.com/new-and-extended-functionality/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:

``` php
var_dump(PHP_INT_MIN, PHP_INT_MAX);
```

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

    int(-9223372036854775808)
    int(9223372036854775807)

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`?

``` php
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`:

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

---

Previous: [Consistent 64-bit Support](https://php7explained.com/new-and-extended-functionality/mathematics/consistent-64-bit-support/index.html.md) | Next: [gmp_random_seed()](https://php7explained.com/new-and-extended-functionality/mathematics/gmp_random_seed/index.html.md)
