integer division in php

Just cast it to an int:

$result = (int)(6 / 2);

For whatever reason, it's much faster than intval().

Edit: I assume you are looking for a general integer division solution. Bit-shifting is a special case for dividing by (or multiplying by) powers of 2. If that interests you then:

a / b^n = a >> n where a, b, n are integers

so:

a / 2 = a / 2^1 = a >> 1

But two caveats:

  1. Many compilers/interpreters will do this for you automatically so there is no point second guessing it;

  2. Unless you're doing this division at least 100,000 times in a single script execution don't bother. It's a pointless micro-optimization.

To further elaborate on (2), yes (int) is faster than parseInt() but does it matter? Almost certainly not. Focus on readable code and a good algorithm. This sort of thing is an irrelevant distraction.


if it's division by 2, the fastest way to do it is bit shifting.

5>>1 = 2
6>>1 = 3

and so on and so forth. What it does is just shift the bits to the right by 1 bit, thus dividing the number by 2 and losing the rest

1110 >> 1 =  111
1011 >> 1 =  101
1011 >> 2 =   10 //division by 4
1011 << 1 =10110