php

How to Use the intdiv() Function in PHP

When performing division operations in PHP, you may come across scenarios where you specifically need to divide two numbers and obtain an integer result. In such cases, the intdiv() function in PHP comes to your aid which allows you to divide two numbers and return the quotient as an integer value.

In this article, we will explore how to use the intdiv() function effectively in PHP.

What is intdiv() Function in PHP?

The intdiv() function is the built-in PHP function that is used to perform the division of the integers of two numbers and returns the quotient without any reminder. This is a convenient way to perform the division in PHP without using any additional functions. The intdiv() function does not round the results, it returns the whole number quotient.

Syntax

The syntax for using the intdiv() function is as follows:

intdiv($dividend, $divisor);

The intdiv() function accepts two parameters: dividend and divisor. The dividend is the compulsory parameter of this function that specifies the number to be divided, and the divisor specifies the number for dividing the given dividend. The intdiv() function returns the value with an integer data type, after dividing two numbers.

Note: If you pass the divisor 0 then this function returns the error.

Example 1

Consider the following example of using the intdiv() function in PHP. In this sample code, we have passed the multiple values to the intdiv() function.

<?php
echo intdiv(8, 4) . "\n";
echo intdiv(6, 2) . "\n";
echo intdiv(-5, -2);
?>

Example 2

Below is another code snippet of using the intdiv() function in PHP:

<?php
$dividend = 28;
$divisor = 3;
$result=intdiv($dividend, $divisor);
echo "The result of the $dividend by $divisor is: " .$result;
?>

Example 3

If you divide the negative number by the positive number the result will be negative:

<?php
$dividend = -19;
$divisor = 3;
echo intdiv($dividend, $divisor);
?>

Bottom Line

The intdiv() function in PHP provides a convenient and accurate way to perform integer division without rounding or returning any fractional part. It performs precise calculations and returns the integer number of two numbers after dividing them. By incorporating the intdiv() function into your PHP code, you can perform integer division with ease and accuracy.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.