5

Can someone please explain what is going on here?

-1 % 7 = 6 https://www.wolframalpha.com/input/?i=-1%257 ...but

echo (-1 % 7)."\n";    // prints -1 WRONG
echo fmod(-1,7)."\n";  // prints -1 WRONG

I also tried these examples from php.net, all of them return correctly.

echo (5 % 3)."\n";           // prints 2
echo (5 % -3)."\n";          // prints 2
echo (-5 % 3)."\n";          // prints -2
echo (-5 % -3)."\n";         // prints -2

PHP is giving me a result I can't explain for -1%7. It's not overflowing the int but I tried fmod anyways, but I'm still having my same issue (ie Doesn't look to be this issue: php modulo return wrong result)

KPK
  • 442
  • 1
  • 5
  • 15

3 Answers3

3

So, turns out -1 is a correct answer. It's the "negative remainder". I'm not a math major, I wasn't aware there was another valid-ish answer. I'm looking exclusively for the non-negative remainder (the normal answer).

Turns out I can use gmp_mod for that. https://www.php.net/manual/en/function.gmp-mod.php

This helped me get on the right track: https://www.omnicalculator.com/math/modulo

KPK
  • 442
  • 1
  • 5
  • 15
2

If you want to get the true modulo of a negative number in PHP, you have to do two remainder operations, the second after adding the number you are doing the modulo by to make the input to the operation positive:

$a = ((-1 % 7) + 7) % 7;
echo $a;
$a = ((4 % 7) + 7) % 7;
echo $a;

Output

6
4

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
1

In PHP, the operator % returns the remainder of the division, not the modulo.

From the docs: Arithmetic Operators

$a % $b Modulo Remainder of $a divided by $b.

And more:

The result of the modulo operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a

So, if you want the mathematically true modulo, you'll need to add more calculation, like in the function below:

function modulo( $dividend, $divisor ){
  return ( $dividend % $divisor + $divisor ) % $divisor;
}
Caconde
  • 4,177
  • 7
  • 35
  • 32
  • Actually modulo and remainder mean the same thing here, as in programming a modulo operation is strictly for finding the remainder. – Webber Sep 02 '19 at 22:03
  • 1
    I disagree. **Modulo** and **Remainder** are not the same thing. In Modular Mathematics, `-1%7 = 6` while in PHP `-1%7 = -1`. It's totally different. The OP accepted the programming perspective, but taking that info as true from modular mathematics point of view is totally incorrect. – Caconde Sep 02 '19 at 22:35
  • 1
    Fair enough, however I'd say we have to take into account the answer from @KPK, elaborating a bit on your above comment. – Webber Sep 03 '19 at 07:42