How to divide numbers without remainder in PHP?

PhpMathDivision

Php Problem Overview


How does one divide numbers but exclude the remainder in PHP?

Php Solutions


Solution 1 - Php

Just cast the resulting value to an int.

$n = (int) ($i / $m);

Interesting functions (depending on what you want to achieve and if you expect negative integers to get devided) are floor(), ceil() and round().

Solution 2 - Php

PHP 7 has a new built-in function for this named intdiv.

Example:

$result = intdiv(13, 2);

The value of $result in this example will be 6.

You can find the full documentation for this function in the PHP documentation.

Solution 3 - Php

For most practical purposes, the accepted answer is correct.

However, for builds where integers are 64 bits wide, not all possible integer values are representable as a double-precision float; See my comment on the accepted answer for details.

A variation of

$n = ($i - $i % $m) / $m;

(code taken from KingCrunch's comment under another answer) will avoid this problem depending on the desired rounding behavior (bear in mind that the result of the modulus operator may be negative).

Solution 4 - Php

In addition to decisions above like $result = intval($a / $b) there is one particular case:

If you need an integer division (without remainder) by some power of two ($b is 2 ^ N) you can use bitwise right shift operation:

$result = $a >> $N;

where $N is number from 1 to 32 on 32-bit operating system or 64 for 64-bit ones.

Sometimes it's useful because it's fastest decision for case of $b is some power of two.

And there's a backward (be careful due to overflow!) operation for multiplying by power of two:

$result = $a << $N;

Hope this helps for someone too.

Solution 5 - Php

or you could just do intval(13 / 2) gives 6

Solution 6 - Php

use modulo in php:

$n = $i % $m;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneomeroffView Question on Stackoverflow
Solution 1 - PhpKingCrunchView Answer on Stackoverflow
Solution 2 - PhpRemco BeugelsView Answer on Stackoverflow
Solution 3 - PhpraloktView Answer on Stackoverflow
Solution 4 - PhpFlameStormView Answer on Stackoverflow
Solution 5 - PhpAlexView Answer on Stackoverflow
Solution 6 - PhpMarcoView Answer on Stackoverflow