1

I'm using the following working code to wrap every 3 elements in a div:

$count = 1

foreach( $names as $name ):

  if ($count%3 == 1) {
    echo '<div class="wrap">';
  }

  echo $name;

  if ($count%3 == 0) {
    echo '</div>';
  }

  $count++;

endforeach;

if ($count%3 != 1) echo "</div>";

That returns:

<div class="wrap">
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
</div>

So far so good.. but i want the second wrapped set to have 4 "name" elements like so:

<div class="wrap">
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
</div>
<div class="wrap">
  name
  name
  name
</div>

Every 3 items should be wrapped in the div, except the second set which will have 4 items.

Or another way to explain: items 4 to 8 will be wrapped in a div while every other 3 items will be wrapped in div.

How can this be achieved?

1 Answer 1

2

Add special cases for the first two DIVs, and adjust the modulus for the ones after that.

$count = 1

foreach( $names as $name ):
    if ($count == 1 || $count == 4 || ($count > 5 && $count % 3 == 2)) {
        echo '<div class="wrap">';
    }
    echo $name;
    if ($count == 3 || $count == 7 || ($count > 7 && $count % 3 == 1)) {
        echo '</div>';
    }
    $count++;
endforeach;
// Finish the last block -- lots of different cases
if ($count < 4 || ($count > 4 && $count < 8) || ($count > 8 && $count % 3 != 2)) {
    echo '</div>';
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! It is now wrapping div within divs. What should the last one be after the endforeach;?if ($count%3 != 1) echo "</div>"; I use that to make sure the div is closed
I added that to the answer, it's actually the trickiest part!
And I got it wrong at first, because I forgot that we incremented $count already. It should be right now.
Hmm this is strange. It returns the first wrap set with 3 items which is ok but the second wrap set has the remaining wrap sets within it.
Hmm this is strange. It returns the first wrap set with 3 items which is ok but the second wrap set has the remaining wrap sets within it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.