Jump to content

Php Modulus 1%3 And 2%3


DaniIvanov

Recommended Posts

A quick question on the modulus operator. If you look at the code everything from 3 % 3 is very clear 3/3 = 1r0 , 4/3 = r1, 5/3 =r2.

What i cannot get and i ve searched google for the answer is why 1%3 is equal to 1 when 3 fits 0 times in 1, and why is 2 % 3 equal to 2 when 2 fits 0 times in 3 as well?

 

echo 0 % 3 . "<br />"; // result 0
echo 1 % 3 . "<br />"; // result 1
echo 2 % 3 . "<br />"; // result 2
echo 3 % 3 . "<br />";
echo 4 % 3 . "<br />";
echo 5 % 3 . "<br />";
echo 6 % 3 . "<br />";
echo 7 % 3 . "<br />";
echo 8 % 3 . "<br />";
echo 9 % 3 . "<br />";
echo 10 % 3 . "<br />";

Link to comment
https://forums.phpfreaks.com/topic/269306-php-modulus-13-and-23/
Share on other sites

I think you're confused about what a remainder is. It's the single digit left over that doesn't fit into the divisor at all.

 

0/3 = 0 (no remainder)

1/3 = 0 (with a remainder of 1).

2/3 = 0 (with a remainder of 2).

3/3 = 1 (no remainder)

etc..

7/3 = 2 (with a remainder of 1).

8/3 = 2 (remainder = 2).

 

Etc.

 

This might help as well:

http://en.wikipedia.org/wiki/Remainder

Or maybe this one more so:

http://en.wikipedia.org/wiki/Modulo_operation

 

In most practical uses, the % is only going to be checked to see when it == 0. For things like loops where you want to color every other row, or have a row with $x cells, etc.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.