intdiv()
Today, we will discuss the intdiv() function in PHP. This function is used to perform integer division and return the quotient.
The intdiv() function in PHP performs integer division and returns the quotient.
What is the intdiv() Function?
The intdiv() function is a built-in PHP function that performs integer division and returns the quotient. It takes two arguments and returns the result as an integer, truncated towards zero. If either argument is a float, it is truncated towards zero before the division is performed. For example, intdiv(-7, 2) returns -3, demonstrating that the result is always truncated toward zero rather than rounded down.
How to Use the intdiv() Function
Using intdiv() is straightforward. Here is a basic example:
How to Use the intdiv() Function in PHP?
<?php
$dividend = 10;
$divisor = 3;
// Perform integer division using the intdiv() function
$quotient = intdiv($dividend, $divisor);
// Output the quotient
echo $quotient;
?>In this example, we define two integer variables and pass them to intdiv() to calculate the quotient. The result is then printed to the screen.
Note: Dividing by zero throws an
Error(specificallyDivisionByZeroErrorin PHP 8+). Always ensure the divisor is not zero.
Conclusion
The intdiv() function provides a reliable way to handle integer division in PHP. By understanding its truncation behavior and edge cases, you can integrate it effectively into your applications.
Practice
What does the intdiv() function in PHP do?