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
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.

Edited by Jessica
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.