0

I need some advice on this one. If I have a PHP foreach loop:

<div class="wrapper">
  <?php foreach ($item as $element): ?>
    <!-- some HTML of $element -->
  <?php endforeach; ?>
</div>

and after every 5th $item I want to create a new .wrapper with the next 5 items in the foreach. And redo this step until all are through. The output should be like:

<div class="wrapper">
  <!-- some HTML of $element 1 -->
  <!-- some HTML of $element 2 -->
  <!-- to $element 5 -->
</div>

<div class="wrapper">
  <!-- some HTML of $element 6 --> 
  <!-- to $element 10 -->
</div>

Do I need to run another foreach outside to make this possible?

Thanks

3
  • Actually no you have to do the opossite,aka to echo the wrapper in for loop every 5 $items Commented Feb 19, 2015 at 11:44
  • @Akis and how exactly to I ask for every 5 items. Commented Feb 19, 2015 at 11:44
  • you can add a counter and compute the modulo 5 ;) exactly as neil proposed Commented Feb 19, 2015 at 11:51

3 Answers 3

3

Try this

$i = 0; 
<?php 
    foreach ($item as $element) { 
        if($i%5==0) echo "<div class=\"wrapper\">";
?>

        <!-- some HTML of $element -->

<?php
        if($i%5==4) echo "</div>";
        $i++;
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

I think that this code will not do the job. It will wrap the first element in the div, then the fifth, etc... All the other elements will be outside the div. Did you test it?
2

Possible solution:

<div class="wrapper">
    <?php $counter = 0; ?>
    <?php foreach ($item as $element): $counter++; ?>
        <!-- some HTML of $element -->
        <?php if ($counter % 5 === 0 && $counter !== count($item)): ?>
            </div>
            <div class="wrapper">
        <?php endif; ?>
    <?php endforeach; ?>
</div>

Comments

0

Try this

$i = 0;
<?php foreach($item as $element) : ?>
        <?php if($i == 0) : $i=5; ?>
              <div class="wrapper">
        <?php endif; ?>

           <!-- some HTML of $element -->
        <?php $i -= 1; if($i == 0) : ?>
          </div>
        <?php endif; ?>
  <?php endforeach; ?>

Comments

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.