PHP intdiv
intdiv returns the integer quotient of two integers, truncating toward zero. The remainder operator gives the unallocated units.
A simple example
intdiv
- Start with 7 and 3
- Do this Divide as integers
- Result 2
<?php
echo (intdiv(7, 3)), PHP_EOL;
2
Syntax
intdiv($units, $packSize)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Split quantities into whole packs and a remainder
A batch of items must be divided into pages, containers or work units of fixed size. Account for the final partial group so the last few items are neither lost nor counted as a full batch incorrectly.
<?php
declare(strict_types=1);
foreach ([13, -13] as $units) {
printf("%d packs, %d left\n", intdiv($units, 6), $units % 6);
}
2 packs, 1 left -2 packs, -1 left
For negative quantities the quotient truncates toward zero and the remainder takes the dividend's sign. A zero divisor raises DivisionByZeroError.
Make complete paint sets
A studio has 29 paint tubes and puts six in each set. It lists only sets that can be handed out complete.
Four sets use 24 tubes. Five tubes stay on the shelf.
Share a complete batch of tickets
Forty tickets are shared equally among eight activity groups. The organizer records the whole-number share per group.
Every ticket is allocated because the division has zero remainder.