user1251698
user1251698

Reputation: 2143

PHP simple grouping items in while loop

In the following while loop, each div item is wrapped in a li.

<php while (condition){
    <li><div>Item</div></li>
<?php } ?>

In the above loop, I want to to wrap 2 div items inside a li, so that I can get similar output:

<li>
    <div>Item</div>
    <div>Item</div>
</li>

<li>
    <div>Item</div>
    <div>Item</div>
</li>

 <li>
    <div>Item</div>
</li>

So, I am trying this, but this wraps one div inside a li and leaves other without li.

<?php 
    while (condition){
    $i++;
    if($i % 2 == 0) { echo "<li>"; }
    ?>
        <div>Item</div>
<?php 
    if($i % 2 == 0) { echo "</li>"; }
     } //end loop 
?>

Upvotes: 1

Views: 911

Answers (2)

adeneo
adeneo

Reputation: 318182

It would look something more like :

<?php
    $i = 1;
    while ($i < 10){
    $i++;
    if($i % 2 == 0) { echo "<li>"; }
    ?>
        <div>Item</div>
<?php 
    if($i % 2 == 1) { echo "</li>"; }
     } //end loop 
?>

Upvotes: 1

Jon
Jon

Reputation: 437336

The general idea in these cases is:

  1. on each iteration, open a new group if $i % $itemsPerGroup == 0
  2. print an item
  3. before looping, close the current group if ++$i % $itemsPerGroup == 0
  4. when the iteration ends close the last open group -- one will exist if $i % $itemsPerGroup != 0

So:

$i = 0;
while (condition){
   if($i % 2 == 0) { echo "<li>"; } // #1
   echo "<div>Item</div>"; // #2
   if(++$i % 2 == 0) { echo "</li>"; } // #3
}

if ($i % 2 != 0) { echo "</li>"; } // #4

Upvotes: 3

Related Questions