Thread: \$i++ % 2 == 0

1. \$i++ % 2 == 0

alright, i'm trying to understand the way this works...i mean i do, but i want to see why...i think...lol confused?

alright, i'm alternating row colors...
i use this:
PHP Code:
``` \$i = 0; if (\$i++ % 2 == 0) { \$bg = "#0E377C"; } else { \$bg = "#266BB1"; }  ```
the way i see it is i will first equal zero no problem there, but the next line, to me would mean that i is going to step up (to 1 the first time, right?) and it needs to equal 0 to equal \$bg = "#0E377C", otherwise it will equal \$bg = "#266BB1", but what are the nubers exactly..

like why does i incrementing by one need the mod 2? what does that equal anyways...and so does this mean that everyother increment equals 0?

can someone break it down so that i might understand those two lines?

thanks

2. wow, another one I can explain

PHP Code:
``` \$i = 0; // If i++ -- means add one, sorthand for i = i + 1 // % 2 -- means if i divided by 2 is equel to 0 then.... if (\$i++ % 2 == 0) { \$bg = "#0E377C"; } // if i divided by 2 not equel to zero... // else.... else { \$bg = "#266BB1"; }  ```

3. [homer]DOH!!!![/homer]

well that makes plenty of sense...and now that i understand the math of it, i can see why it works the way it does...

thanks a bunch!!!!

4. I don't venture into the PHP forum much Glad I could help

5. Well essentially the remainder of a division of the number by the second number. Because of odd and even numbers, every other number (integer) can be divided perfectly by 2, which provides the alternating colours.

This is a nice variation building in the integer increment, others follow the same principle:

PHP Code:
``` \$i = 0; while ( some condition/collects data ) { if (\$%2) {\$bg = "#0E377C";} else {\$bg = "#266BB1";} \$i++; }  ```
Using ternary operator:

PHP Code:
``` \$i = 0; while ( some condition/collects data ) { \$bg = ( (\$i++ % 2) ? "#0E377C" : "#266BB1" );  }  ```

6. There's an even nicer way (IMHO) to do this:

PHP Code:
``` for( \$i = 1 ; \$i <= 10 ; \$i++ ) {   \$colour = ( \$colour == "#0E377C" ) ? "#266BB1" : "#0E377C" ;   print '<font color="' . \$colour . '">Hello</font><br />' ; }  ```
Obviously you can control your loop as you want..

Matt.

7. Ah yes I remember seeing that. Really ingenius technique and so simple, must remember it.

8. Originally posted by platinum
PHP Code:
``` // % 2 -- means if i divided by 2 is equel to 0 then....  ```
Like other people hinted at, % is the modulus operator, not the division operator. So what we're really finding is the remainder of the division, not the result of the division itself.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•