Jump to content

Loop horizontally


Recommended Posts

<?php 

// Make dummy array
$array = range(0,32);

// This will keep track of how many rows we've echo'd
$i = 0;
// This tells us how many columns
$cols = 3;
$total = count( $array );

echo '<table><tr>';
foreach( $array as $value ) {
// Echo the value in a cell
echo '<td style="border:1px solid black;">'.$value.'</td>';
// Increase our counter by 1 before we check
$i++;
// Check to see if we need to start a new row by using the modulus operator
// It'll give us the remainder of the two numbers divided.
// We check if $i != $total to make sure we don't have a redundant empty row
// at the end
if( ($i % $cols) == 0 && $i != $total ) echo '</tr><tr>'; // Start a new row
}
// Now after the foreach, if we have an odd number of results, we'll have an
// extra empty column we need to fill, we can do this automatically
while( ($i % $cols) != 0 ) {
echo '<td> </td>';
$i++;
}
echo '</tr></table>';

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.