Library contents

PHP intdiv

intdiv returns the integer quotient of two integers, truncating toward zero. The remainder operator gives the unallocated units.

A simple example

intdiv

  1. Start with 7 and 3
  2. Do this Divide as integers
  3. Result 2
Three fits into seven twice. Integer division discards the remaining fraction here.
lesson.php
<?php
echo (intdiv(7, 3)), PHP_EOL;
Output
2

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output line2 packs, 1 left
lesson.php
<?php
declare(strict_types=1);

foreach ([13, -13] as $units) {
    printf("%d packs, %d left\n", intdiv($units, 6), $units % 6);
}
Output
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.

PHP documentation for intdiv

Advertisements

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.

Given29 tubes · 6 per set
Worked result4 sets

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.

Given40 tickets · 8 groups
Worked result5 tickets

Every ticket is allocated because the division has zero remainder.