How do I wrap columns two and two inside a loop?

I am trying to wrap two columns inside a div row from inside a php loop.

I came up with this test, but it fails no matter what I do. This is the closest I can come, I can't see where this logic fails.

Take a look:

<?php $i = 0; ?>
<?php while($i < 11) : ?>

  <?php if ($i % 2 === 0) : ?>

    <div class="row">row

  <?php endif; ?>

  <span><?php echo "[" . $i . "]"; ?></span>

  <?php if (!$i % 2 === 0) : ?>

     /row
    </div>

  <?php endif; ?>

  <?php $i++; ?>
<?php endwhile; ?>

      

The result is:

row [0] [1] /row
row [2] /row
[3] /row
row [4] /row
[5] /row
row [6] /row
[7] /row
row [8] /row
[9] /row
row [10] /row

      

Here we can see that the first line works fine, but then it becomes incorrect somewhere in the logic, the question is where?

+3


source to share


4 answers


Made small changes to your code.

  <?php $i = 0; 
       while($i <= 11) :  
       if($i%2==0){
        echo '<div class="row"> Row';
       } 
         echo "[" . $i . "]"; 

       if($i%2!=0){
        echo " row </div>";
       }
       $i++; 
     endwhile; ?>

      



He will output

 Row[0][1] row
 Row[2][3] row
 Row[4][5] row
 Row[6][7] row
 Row[8][9] row
 Row[10][11] row

      

+1


source


A different column counter is used. Tested and seems to work: http://sandbox.onlinephpfunctions.com/code/7374de00caef8a3f6b89a6196093326e8133c021



$col = 0;
for($i = 0; $i < 11; $i++){
  if($i % 2 == 0){
    echo '<div>';
  }

  echo "<span>[".$i."]</span>";
  $col++;

  if($col == 2){
    echo "</div>";
    $opened = false;
    $col = 0;
  }


}

      

0


source


Something like that:

<?php
  $count = 14;
  for($i = 0; $i <= $count; $i += 2) {
    if ($i % 2 == 0) {
       echo('row ');
    }

    echo('['.$i.']');
    if ($i < $count) {
      echo('['.($i+1).']');
    }

    if ($i % 2 == 0) {
       echo(' /row ');
    }
  }
?>

      

Result:

row [0][1] /row 
row [2][3] /row 
row [4][5] /row 
row [6][7] /row 
row [8][9] /row 
row [10][11] /row 
row [12][13] /row 
row [14] /row 

      

0


source


try it

<style>
div {
    border: 1px red solid;
    width: 100px;
    padding: 3px;
    margin: 3px;
    text-align: center;
}
</style>
<?php

$i = 0;
while ($i < 11) :
$row = $i % 2 === 0;
?>

    <?php if ($row): ?><div><?php endif;?>
    <span><?php echo '[' . $i . ']'; ?></span>
    <?php if (!$row): ?></div><?php endif;?>

<?php
    $i++;
endwhile; ?>

      

output:

enter image description here

0


source







All Articles