Print array as table


Often you have an array of data which you require to print as an html table. Although css is nowadays the de facto standard for web page layouts, tables should still be used for tabular data. A recent post on webhostingtalk churned out the old modulo division test - for example if we want 4 columns, test each loop index as we go, and start a new row whenever the remainder is zero.
Mostly a waste of time as we can more easily use array_chunk to split our array in little array chunks, each the right size for a row, then simply print them.
We can then create a little re-usable function, simply pass the number of columns required, along with the array, and we get back the exact table we want. Much faster and neater. Here's a little example:


<?php
$columns=3;
$array=array("one", "two", "three","four","five","six","seven","eight");
$rows= array_chunk($array,$columns);
print "<table>\n";
foreach ($rows as $row) {
print "<tr>\n";
foreach ($row as $value) {
print "<td>" . $value . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
?>