http://ideone.com/CzLlJH

<?php $count = 15; $row_count = 3; for($i = 0; $i < $count; $i++) { echo ' <div class="row{NUM}"> '.$i.' </div> '; } ?> 

It is necessary that the first three elements be class="row1" , the next three are class="row2" , etc.

Example:

 <div class="row1"> 0 </div> <div class="row1"> 1 </div> <div class="row1"> 2 </div> <div class="row2"> 3 </div> <div class="row2"> 4 </div> <div class="row2"> 5 </div> <div class="row3"> 6 </div> <div class="row3"> 7 </div> <div class="row3"> 8 </div> 
  • one
    good rest, apparently! :) $row = floor($i/3)+1; Ideone - Sergiks
  • @Sergiks, the wrong word is straightforward: D Everything works fine , turn the comment into an answer :) - ModaL

2 answers 2

In order for 3 steps $i , $row do only 1 - it is necessary to round up the whole result of dividing $ i by 3:

 $i floor($i/3) 0 0 1 0 2 0 3 1 4 1 5 1 

In your task, the counting of lines is not from 0, but from 1, therefore +1:

 $row = floor($i/3)+1; 

Total recommended code:

 <?php $count = 15; $row_count = 3; for($i = 0; $i < $count; $i++) { $row = floor( $i / $row_count) + 1; printf('<div class="row%d">%d</div>'.PHP_EOL, $row, $i); } 

Run this code on Ideone .

    You can do the following:

     <?php $count = 15; $row_count = 3; for($i = 0; $i < $count; $i++) { $num = floor($i / $row_count) + 1; echo ' <div class="row'.$num.'"> '.$i.' </div> '; }