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:
- $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 returnfalse
.
Example 1: Basic Integer Division
Output:
Explanation: Dividing 10
by 3
gives a quotient of 3
(the decimal part .33
is discarded).
Example 2: Division with Negative Numbers
Output:
Explanation: When the dividend is negative, the result is still an integer, yielding -3
.
Example 3: Both Negative Numbers
Output:
Explanation: Dividing two negative numbers gives a positive result. Thus, intdiv(-10, -3)
returns 3
.
Example 4: Division by Zero
Output:
Explanation: Dividing by zero results in a warning, and the function returns false
.
Example 5: Using Floats
Output:
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 anE_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:
Output:
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.