This allows you to output valid (x)html tables from an array. You can vary the amount of columns and adjust the look using CSS. Updated to include row highlighting! This was originally posted on 227net and works in PHP4 and up.
<?php
// Text to Table
function table (&$fileArray, $cols, $attribute = false) {
// the number of objects
$total = count($fileArray);
// the leftovers
$calcs = $total - (floor($total / $cols) * $cols);
// start loop
$i = 1;
$n = 1;
// output the table
$table = ($attribute == false) ? "<table>\n" : "<table ". $attribute .">\n";
$table .= "<tr class=\"low\">\n";
foreach ($fileArray as $file) {
$table .= "\t<td>". trim($file) ."</td>";
if (is_int($i / $cols)){
$table .= "\n</tr>\n";
if (($i + 1) <= $total){
// set background class for row
$bgcolor = (++$n & 1) ? "low" : "high";
$table .= "<tr class=\"". $bgcolor ."\">\n";
}
} else {
$table .= "\n";
}
// increment loop
$i++;
}
// start tidy up process
if (!is_int(($i-1) / $cols )) {
$n = 1;
$y = ($cols - $calcs);
$tidy = "";
while ($n <= $y) {
$tidy .= "\t<td> </td>\n";
$n++;
}
$table .= $tidy;
// close the row
$table .= "</tr>\n";
}
// close the table
$table .= "</table>";
return $table;
}
/* Create cols */
$cols = 5;
/* Example one using file() to create an array */
# $filename = "/path/to/text.txt";
# $fileArray = @file($filename);
# echo table ($fileArray, $cols, "id=\"fileArray\"");
/* Example two using a custom array, could be returned from DB query */
$fileArray2 = range(1, 36);
echo table ($fileArray2, $cols, 'class="fileArray2"');
?>