PHP modulo operator (%) returns negative numbers

The PHP modulo operator, %, returns negative numbers. e.g. -3%7 == -3. Other languages will wrap the negative to produce a positive number, e.g. -3%7 == 4.

To implement a true modulo operator, you have to write a custom function:

function truemod($num, $mod) {
  return ($mod + ($num % $mod)) % $mod;
}

Example: trumod(-3,7) == 4

References

Last modified: 09/09/08 17:20:04
Go to top

Related Pages

No related pages or links.

Login/out

Login

Forgot Password?
Go to top
Go to top