PHP intdiv() function


The intdiv() function in PHP performs integer division, returning the integer quotient of two numbers. It divides the first argument (the dividend) by the second argument (the divisor) and truncates the result to an integer, effectively discarding any decimal portion.

Syntax:

intdiv(int $dividend, int $divisor): int
  • $dividend: The number to be divided.
  • $divisor: The number by which to divide. This must not be zero.
  • Return Value: Returns the integer quotient as an integer. If the divisor is zero, it will trigger an E_WARNING and return false.

Example 1: Basic Integer Division

<?php echo intdiv(10, 3); ?>

Output:

3

Explanation: Dividing 10 by 3 gives a quotient of 3 (the decimal part .33 is discarded).

Example 2: Division with Negative Numbers

<?php echo intdiv(-10, 3); ?>

Output:

-3

Explanation: When the dividend is negative, the result is still an integer, yielding -3.

Example 3: Both Negative Numbers

<?php echo intdiv(-10, -3); ?>

Output:

3

Explanation: Dividing two negative numbers gives a positive result. Thus, intdiv(-10, -3) returns 3.

Example 4: Division by Zero

<?php echo intdiv(10, 0); ?>

Output:

Warning: Division by zero

Explanation: Dividing by zero results in a warning, and the function returns false.

Example 5: Using Floats

<?php echo intdiv(10.5, 3.5); ?>

Output:

2

Explanation: Even though the inputs are floats, intdiv() converts them to integers for the calculation. The result is 2 because the float division 10.5 / 3.5 yields approximately 3, which is truncated.

Key Points:

  • Integer Division: intdiv() specifically handles integer division, ensuring the result is always an integer by truncating any decimal part.
  • Error Handling: If a division by zero occurs, intdiv() will generate an E_WARNING, which can be caught if error handling is implemented in the application.
  • Use Cases: This function is particularly useful when you need precise integer results from division operations, such as calculating the number of whole items in a batch or distributing items evenly.

Example of Practical Use:

<?php $totalItems = 10; $itemsPerBox = 3; $fullBoxes = intdiv($totalItems, $itemsPerBox); echo "Number of full boxes: " . $fullBoxes; ?>

Output:

Number of full boxes: 3

Explanation: In this case, intdiv() is used to determine how many full boxes can be filled with a total of 10 items when 3 items fit in each box.

In summary, intdiv() is a useful PHP function for performing integer division, ensuring that the result is always an integer and helping to avoid errors related to non-integer results.