I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The current way is obviously not good since the action must be performed each time that periodic pattern is fulfilled, and this would require many, many OR operators.

if($a == 14 || $a == 22 || $a == 30 || $a == 38 || $a == 46... until some number){
    do something...

closed as unclear what you're asking by user22815, GlenH7, user40980, gnat, Tulains Córdova Sep 25 '14 at 3:37

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Are the numbers in the sequence all of the form 8k+6? – Ryan Sep 25 '14 at 3:16
  • 1
    Generally you should try if (isSomething($a)) { do something ... } and then you can solve that problem in isSomething, ideally with the solution @Winston Ewert proposed. – back2dos Sep 25 '14 at 6:49
if($a % 8 == 6 && $a >= 14 && a <= some_number)

In general, if you want periodicity, think modulus.


If your test values are not in any specific sequence (are not powers or two, not all even, not all odd, etc) you can use a lookup table to avoid the long if chains:

int test_values[] = { 14, 22, 30, 38, 46, ... };

for (i = 0; i < test_values.length; i++)
    if (input == test_values[i])
        do something...

This way it is also very easy to add more values by just expanding the array. The array of cases can also be initialized from an external config file.


In Python this is fairly descriptive:

if a in range(14, some_number, 8):
    do something

Not the answer you're looking for? Browse other questions tagged or ask your own question.