phploopsfor-loopiterationmodulus

PHP: wrapping each group of 3 elements


I am trying to figure out how to write a loop that will wrap every group of 3 elements. However, for the last iteration, it should wrap whatever is left (be it one, two or three elements)

So basically this kind of pattern:

div
do stuff
do stuff
do stuff
end-div
div
do stuff
do stuff
do stuff
end-div
div
do stuff
do stuff
do stuff
end-div
div
do stuff
end-div

Here is where I'm at so far:

<?php

  $counter = 0;

  for ($i = 1; $i <= 10; $i++) {

    if (($counter + 1) % 3 == 0) {
      echo 'div <br />';
    }
    echo 'do stuff <br />';
    if (($counter + 1) % 3 == 0) {
      echo 'end-div <br />';
    }

    $counter ++;
  }

?>

This is giving me the following:

do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 

Can anyone see where I'm going wrong?


Solution

  • In other words, you need to write div before each group of three items and end-div after each group of three items:

    // $counter always tells the number of processed items
    $counter = 0;
    
    for ($i = 1; $i <= 10; $i++) {
        // before a group of three, $counter is a multiple of three
        if ($counter % 3 == 0) {
            echo 'div <br />';
        }
    
        // process the item then count it
        echo 'do stuff <br />';
        $counter ++;
    
        // after a group of three, $counter is a multiple of three
        if ($counter % 3 == 0) {
            echo 'end-div <br />';
        }
    }
    
    // close the last group if it is not complete
    if ($counter % 3 != 0) {
        echo 'end-div <br />';
    }
    

    Check it online.