PHP HelpPHP Help

Online Community that helps beginners learn PHP,
and webmasters solve PHP coding problems

since 1999

Formatting a List as a Table

Displaying Results in Two Columns

The tricky part is that we do not know how many items will be in the results. So we have to find the mid-point in the list, so that if we have 12 items, the first 6 will go in the left column and the last six will go in the right column. If we have some fractional number of items "leftover" we need to put the extras into the rightmost column. So if we have 11 items, we need to put the first 6 in the left column and the remaining 5 in the right column.

We find the mid point by dividing the number of rows in the result by two.

We then need a way to discover which column to put each item into. This is done by using the modulo operator, which is a fun and useful operator commonly used in programs to do many cool things. Modulo produces a cycle of numbers that "wrap around" when math is done. So if we know the index for a row, (row MODULO division_point) acts like a switch telling us which row to put it in. The result of this calculation will be 0 or positive integer for each alternate row.

You can see how this works:

0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
mysql_num_rows($result) / 2;


while ( 
$row mysql_fetch_array($result) ) {

$item sprintf("<p class=item><b><a href=\"index.php?category=%s\">%s</a></b> (%s)<br><span class=description>%s</span></p>",$row[category],$row[category],$row[items],$row[Description]);

$i $division_point) {
$b .= "$item";
    else {
$a .= "$item";

<tr valign="top">

    <td><?php echo $a?></td>
    <td><?php echo $b?></td>


Note:  you may wonder why the $b comes before the $a in the conditional.

If you have only two categories, the sequence is:

$i,($i % $division_point)

both are zero. Now if($i % $division_point) condition will be satisfied when ($i % $division_point) is positive, non-zero. So it does the else. I flip it to do the b side on positive. It's a little counterintuitive, since you normally expect the left column to come first, then the right, but we're talking about program logic here, not layout. Of course, you could just change the HTML to output $b to the left column and $a to the right side, but that's probably more confusing, since I name $a as left because A comes before B and English reads right to left, making it easier for a novice to drop the PHP snippets into their code.

Pages:  1   2Related Forum Topics   |   More Tutorials »

Copyright © 2018