1

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 
?>

2 Answers 2

3

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
1

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 
?>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.