2

I have some loop. How can i optimize this code that it would be executed each 12 items starting from 2nd item. I'm using hardcoded code for each of +12 item, but of course this is not a good solution :) I know it's easy to do and i was trying to do it with modulus operator, however it worked somehow incorrectly.

<?php if( ($counter == 2) || ($counter == 14) || ($counter == 26) || ($counter == 38) || ($counter == 50) || ($counter == 62) || ($counter == 74) || ($counter == 86) || ($counter == 98 .... ?>

Thanks for help!

MIC
  • 135
  • 2
  • 13
  • It might be useful for you to include the modulus statement you attempted. That way, we can help to clear any misconceptions you might have of the use of the modulo operator. – shrmn Mar 02 '16 at 09:18

1 Answers1

5

Answer

Take a look at the Modulus operator (%):

<?php
    if ( ( $counter - 2 ) % 12 == 0 ) {
        //....
    }
?>

Explanation

The Modulus operator ($a % $b) is the remainder of $a divided by $b.

  • $counter - 2 - as you're starting with an offset of 2, remove that from $counter
  • % 12 - will return the remainder of $counter - 2 divided by 12
  • == 0 - if the above returns 0, you know that it is exactly divisible
Ben
  • 8,894
  • 7
  • 44
  • 80