3

How can I write a modulus that will select the following iterations in sequence?

1, 4, 5, 8, 9, 12, 13 etc (+3+1r)

I'm working within a loop and counting posts (iterations).

So for example, I could catch every third post (1, 4, 7, 10) by:-

if ($i % 3 == 1) { echo 'something here'; } 

But how can I write one that will catch 1, 4, 5, 8, 9, 12, 13?

zigojacko
  • 1,983
  • 9
  • 45
  • 77

2 Answers2

4

I'm not quite sure about your algorithm, but it seems like you try to get every 3rd and 4th post not (starting at 0). The fitting code would be:

if(($i % 4 == 0 || $i % 4 == 1) && $i != 0) { /* do stuff */ }
Sebb
  • 871
  • 6
  • 16
3

Sidenote: If you're curious about the closed form formula:

enter image description here

in case you need to pick up a single n-th term from the sequence.

Otherwise I would suggest using a modulus (like suggested by @Sebb) if you need it in your loop.

birgire
  • 11,258
  • 1
  • 31
  • 54
  • 1
    Crap, are you a mathematician, lol :-). I'm busy with something involving 4, as there is a sequence involving 4 and the modulus. I would like to see a proper solution with that formula though, lol. Will probably post something much later :-) – Pieter Goosen Jan 26 '15 at 13:10
  • @PieterGoosen I did math+physics at uni but that is getting cloudy ;-) I think the modulus version might be faster than calculating the formula in a loop. The formula might be easier to use if one only needs to pick up the n-th term. – birgire Jan 26 '15 at 13:21
  • AHA! Thought I missed something, lol. Last time I got dirty into maths was at school 20 years ago. Still, you get my upvote for this wishful thinking :-) – Pieter Goosen Jan 26 '15 at 13:43
  • Thanks for teaching me another useful thing about W|A ;) I would have never thought of this solution. – Sebb Jan 26 '15 at 14:03
  • 1
    yes W-A is amazing ;-) ps: I did a test [here](http://3v4l.org/GXYe4) to generate the sequence from the formula. – birgire Jan 26 '15 at 14:11