51

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

3
  • 5
    Can you clarify what you mean by reminder?
    – Kartik
    Apr 26, 2011 at 23:30
  • 1
    Kartik: 13 / 2 = 6 remainder 1, because two goes into thirteen six times evenly, leaving a total of one left, which is the remainder.
    – Andrew M
    Apr 26, 2011 at 23:31
  • 4
    Kartik was making a joke about how the requester misspelled remainder. Apr 26, 2011 at 23:34

6 Answers 6

95

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().

1
  • This is, strictly speaking, a bad idea. While it will work well for small values (including all 32bit ints), floats can't represent all 64bit integers. If $i is 2^54+2 and $m is 2, the result of the division can't be 2^53+1, as that is not representable as a double-precision float (I can't test what the actual result on a 64bit system would be right now).
    – ralokt
    Aug 11, 2016 at 14:38
27

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.

8

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

0

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.

-1

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

-9

use modulo in php:

$n = $i % $m;
2
  • 4
    -1 - Not only does this not answer the question, it provides what the question specifically asked to omit: the remainder.
    – danorton
    Feb 28, 2014 at 7:12
  • 5
    For those who like overkill: It can work with module $n = ($i - $i % $m) / $m; :D
    – KingCrunch
    Mar 3, 2014 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.