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


Last modified: 09/09/2008 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top