Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: wrapping each group of 3 elements [duplicate]

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?


2 Answers

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.

like image 111
axiac Avatar answered Dec 06 '25 00:12

axiac


There's no need to use separate $counter variable, make use of $i variable in the for loop itself.

echo 'div <br />';
for ($i = 0; $i < 10; $i++) {
    if($i != 0 && $i % 3 == 0)
        echo 'end-div <br /> div <br />';
    echo 'do stuff <br />';
}
echo 'end-div';
like image 35
Rajdeep Paul Avatar answered Dec 06 '25 00:12

Rajdeep Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!