Current Location: Home> Latest Articles> How to Get the Integer Part of a Division Result in PHP

How to Get the Integer Part of a Division Result in PHP

M66 2025-08-05

How to Get the Integer Part of a Division in PHP

In PHP development, it's common to need the integer portion of a division result. This can be easily achieved using type casting to convert the result into an integer.

Using Type Casting to Truncate Division Results

To extract the integer part of a division between two numbers, use the following syntax:

(int) ($dividend / $divisor);

Where:

  • $dividend is the number to be divided (the dividend)
  • $divisor is the number you are dividing by (the divisor)

By casting the result to an integer using (int), PHP will truncate the decimal portion and return only the whole number part.

Example Code

Here’s a practical example demonstrating integer division in PHP:

$dividend = 20;
$divisor = 5;

$quotient = (int) ($dividend / $divisor);
echo $quotient; // Output: 4

This example uses type casting to ensure only the integer part of the division is returned.

Important Notes

  • Make sure the divisor is not zero, as division by zero will cause a runtime error.
  • Using (int) is a quick and reliable method for truncating division results to whole numbers.
  • For more precise control, you can also consider using functions like floor() or intval().

With this method, you can efficiently retrieve the integer portion of a division operation in PHP, improving both code clarity and robustness.