tags:

views:

82

answers:

3
+4  Q: 

PHP Maths Logic

I am trying to set a variable based on some maths logic (to wrap specific html around elements).

I worked half the problem, to hit 0, 3, 6, 9, 12

if(($i % 3) == 0) { // blah }

Now I need to hit the following numbers, 2, 5, 8, 11, 14, etc

What possible maths operation could I do to hit this sequence?

+6  A: 
if($i % 3 == 1)
if($i % 3 == 2)

Modulo returns the remainder, so when you match the 0, you get the 3rd, 6th, 9th, etc, because 0 is left in the division.

So just check for when 1 remains and 2 remains.

Tor Valamo
lol, as i saw the sequence after posting, i thought add one to $i and run the same test. this is even better though. thanks very much, been thinking too long on that one.
esryl
once you get comfortable with all the things modulo can do, you'll become a better programmer. newbies tend to discard it as "something fancy", while it is indeed an essential operator. also: you don't need parens around the expression.
Tor Valamo
+1  A: 

if((($i-2) % 3) == 0) { // blah }

Martin
+2  A: 

Along with Tor Valamo's answer you can notice the pattern of (3 * $i) - 1

(3*1)-1 = 2
(3*2)-1 = 5
(3*3)-1 = 8
   ...
Anthony Forloney