How to perform an action every 5 results? How to perform an action every 5 results? php php

How to perform an action every 5 results?


you could use the modulus operator

for(int i = 0; i < 500; i++){    if(i % 5 == 0)    {        //do your stuff here    }}


For an HTML table, try this.

<?php$start = 0;$end = 22;$split = 5;?><table>    <tr>  <?php for($i = $start; $i < $end; $i++) { ?>    <td style="border:1px solid red;" >         <?= $i; ?>    </td>    <?php if(($i) % ($split) == $split-1){ ?>    </tr><tr>    <?php }} ?>    </tr></table>


It's possible to use a condition with a modulus, as pointed out. You can also do it with nesting loops.

int n = 500;int i = 0;int limit = n - 5(while i < limit){   int innerLimit = i + 5   while(i < innerLimit)   {       //loop body       ++i;   }   //Fire an action}

This works well if n is guaranteed to be a multiple of 5, or if you don't care about firing an extra event at the end. Otherwise you have to add this to the end, and it makes it less pretty.

//If n is not guaranteed to be a multiple of 5.while(i < n){  //loop body  ++i;}

and change int limit = n - 5 to int limit = n - 5 - (n % 5)