PHP Reference ยท Math Functions
PHP intdiv() function
Reference for PHP intdiv(): divide two integers and get the whole-number quotient, truncated toward zero, with DivisionByZeroError, ArithmeticError and examples.
intdiv() divides one integer by another and returns the integer part of the result, truncated toward zero. intdiv(7, 2) is 3. The / operator, in contrast, returns a float unless both operands divide evenly.
Use it for page counts and offsets, converting seconds to minutes, splitting a total into whole groups, and anywhere you need an exact integer answer without floating-point conversion. Together with the modulo operator % it gives you quotient and remainder.
<?php echo intdiv(17, 5); // 3 echo 17 % 5; // 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
intdiv(int $num1, int $num2): int
| Name | Description |
|---|---|
$num1 |
The dividend (the number being divided). |
$num2 |
The divisor. |
Return value: the quotient as an int, with the fractional part discarded (rounded toward zero).
Errors:
DivisionByZeroErrorwhen$num2is0.ArithmeticErrorwhen$num1isPHP_INT_MINand$num2is-1, because the result does not fit in an integer.TypeErrorfor arguments that are not integers (floats with a fractional part are rejected in strict mode, and deprecated in weak mode).
Usage notes
- Truncation, not flooring. For negative results
intdiv(-7, 2)is-3, whilefloor(-7 / 2)is-4. If you want flooring, usefloor(). - Exact for big numbers.
/converts to float when the division is inexact, losing precision above 2^53.intdiv()stays exact. - Remainder:
%also works on integers and has the sign of the dividend. For floats, usefmod(). - Rounding up: the number of pages for
$nitems isintdiv($n + $perPage - 1, $perPage). - Dividing by zero throws
DivisionByZeroErrorfor/,%andintdiv()alike in PHP 8. Usefdiv()if you wantINForNANinstead. - Introduced in PHP 7.0.
Related
fmod(),ceil()andfloor(),round(), Arithmetic operators,abs()- Lessons: Math functions, Numbers