contact subscribe

Programming Tables.

Generating an HTML table from within a program is a simple exercise, but I've too often seen code that complicates an otherwise simple algorithm. The secret lies with the modulo operator (%), which gives you the remainder of one number divided into another. For example, 5 % 4 returns a remainder of one. This arithmetic operation creates a repeating sequence ideal for creating a table.

Some Values of the Modulo Operator
0 % 40
1 % 41
2 % 42
3 % 43
4 % 40
5 % 41
6 % 42
7 % 43
8 % 40

To create a table with four columns and five rows, we create a loop that increments a value by one, calculates the modulo of that value with four and outputs our table accordingly. As the chart on the right shows, when the modulus is equal to zero we start a row, and when the modulus is one less than our column length, we end a row.

Here's the code in PHP:

$columns = 4;
$rows = 5;
$total = $columns * $rows;

print "<table>"; // start the table
for ($i=0;$i<$total;$i++) {
    if (($i%$columns)==0) { 
        print "<tr>\n";
        //every time the sequence starts over 
        //(equal to 0) print out a row
    }

    print "<td>This is the table cell $i.</td>";

    if ( ($columns - ($i%$columns)) == 1 ) {
        print "</tr>\n";
        //when the sequence is one less than the column value
        //end the row
    }
}
print "</table>"; // end the table

Pretty cool. Can’t say that I’ve ever done this progmatically, but when I do…

Posted by: Dan at March 18, 2005 11:41 AM

Post Your Comment




Remember Me?