12

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 6

20
$remainder = $a % $b;
$quotient = ($a - $remainder) / $b;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
16

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

Are you sure we aren't supposed to floor before cast to int?
@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.
No, (int) rounds towards zero while floor rounds towards negative infinity.
1

How about gmp_div_qr function

<?php
$res = gmp_div_qr(11,5);
die(var_dump($res));

Comments

0

the accepted answer will not work with float values.
another way with inbuilt php>(v.4.2.0) method
fmod

$remainder = fmod ( float $x , float $y );
$quotient = ($x - $remainder) / $y;

Comments

0

Try this

$x=10;
$y=3;

$Quotient =(int)($x/$y);
$Remainder = $x % $y;

Comments

0

(PHP 7, PHP 8)

intdiv(int $num1, int $num2): int

Returns the integer quotient of the division of num1 by num2.

$q = intdiv(10, 3);
echo $q; // response=3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.