New Row every x loops

Discussion in 'PHP' started by sbongo, Jan 14, 2008.

  1. #1
    Hi, i need to make the table create a new row every 5 for loops so that the data would like like

    x x x x x
    x x x x x
    x x x x x
    x x

    help appreciated :)
     
    sbongo, Jan 14, 2008 IP
  2. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #2
    
    $newrow = 0;
    echo "<tr>";
    for($i=0; $i<100; $i++){
     echo "<td>data</td>";
     $newrow++;
    if($newrow == 5) echo "</tr><tr>";
    }
    
    PHP:
    Did not test the code. This code will give you basic idea that how can you do it.
     
    greatlogix, Jan 14, 2008 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    You can also use the modulus operator to avoid many if/else statements or counter resetting.

    
    
    if ($newrow % 5 == 0)
    {
        echo "</tr><tr>\n";
    }
    
    PHP:
     
    nico_swd, Jan 14, 2008 IP
  4. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Assuming you have an array of data items $items (could just as easily be a while loop fetching from the database):

    
    echo "<table>";
    $column = 0;
    foreach ($items as $item)
    {
       if (!$column)
          echo "<tr>";
       echo "<td>{$item}</td>";
       $column++;
       $column %= 5;
       if (!$column)
          echo "</tr>";
    }
    if ($column)
       echo "</tr>";
    echo "</table>";
    
    PHP:
    Untested but you can see what's going on...
     
    SmallPotatoes, Jan 14, 2008 IP
  5. sbongo

    sbongo Peon

    Messages:
    986
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    thanks! it works :0
     
    sbongo, Jan 15, 2008 IP