Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't explain php modulo result

Tags:

php

modulo

mod

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)

like image 286
KPK Avatar asked Sep 02 '19 21:09

KPK


People also ask

How does modulo work in PHP?

Modulo is an integer operator, so it converts both the operands to integers before calculating the remainder. So, basically, modulo does integer division and then gives back whatever is left from the dividend. The sign of the value returned by a modulo operation is determined by the sign of the dividend.

How does modulus operator work?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

How can I get mod in PHP?

The fmod() function returns the remainder (modulo) of x/y.

How do you use modulo?

In most programming languages, modulo is indicated with a percent sign. For example, "4 mod 2" or "4%2" returns 0, because 2 divides into 4 perfectly, without a remainder. "5%2", however, returns 1 because 1 is the remainder of 5 divided by 2 (2 divides into 5 2 times, with 1 left over).


2 Answers

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

like image 58
KPK Avatar answered Sep 30 '22 06:09

KPK


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

like image 36
Nick Avatar answered Sep 30 '22 05:09

Nick