6

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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.