Catching iterations using php modulus in an irregular sequence

坚强是说给别人听的谎言 提交于 2020-01-14 18:48:20

问题


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?


回答1:


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 */ }



回答2:


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

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.



来源:https://stackoverflow.com/questions/28150156/catching-iterations-using-php-modulus-in-an-irregular-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!