I can find reminder by "%" operator . But how can I find the quotient at the same time . Suppose I will divide 10 by 3 . If there is any function which will give me the output 3 as quotient and 1 as reminder .
6 Answers
$remainder = $a % $b;
$quotient = ($a - $remainder) / $b;
1 Comment
jrz
It seems correct but seems to require more operations than is necessary... although I like that it doesn't rely on the behavior of php to round down when casting to int.
Use type casting:
$quotient = (int)(10/3)
This will divide 10 by 3 and then cast that result to an integer.
Since functions can only return a single value (not counting pass-by-reference functionality), there's no way to return 2 separate values from a single function call (getting both the quotient and remainder at the same time). If you need to calculate two different values, then you will need at least two statements.
You can, however, return an array of values and use PHP's list function to retrieve the results in what looks like a single statement:
function getQuotientAndRemainder($divisor, $dividend) {
$quotient = (int)($divisor / $dividend);
$remainder = $divisor % $dividend;
return array( $quotient, $remainder );
}
list($quotient, $remainder) = getQuotientAndRemainder(10, 3);
3 Comments
SOFe
Are you sure we aren't supposed to floor before cast to int?
Jeff Lambert
@SOFe It's been awhile now, but I'm pretty sure that casting to int and floor would be doing the same thing, namely throwing away the decimal part and (effectively) rounding down. Doing both would be superfluous.
SOFe
No,
(int) rounds towards zero while floor rounds towards negative infinity.