For a project that I am working on, I am going to need to dynamically create a table of $x amount of elements, and display them in an orderly fashion. For instance, in a table with 4-5 elements per row. The problem with this, is that if you have an array of 10 elements and you decide to split it up into rows of 4, you have two spaces left over which will break the table unless you fill them up with something.
I've devised a way to do this with any array, and it works pretty well, I think. It's a bit late, and I didn't get much sleep last night so I'm kind of fuzzy as to how well I am doing this, or how it could be done better.
Below is the code.
Click here to see it in action.
PHP Code:
<?
$numbers = array( "one", "two", "three", "four",
"five", "six", "seven", "eight",
"nine", "ten" );
if ( !$per_row ) $per_row = 4;
$cellwidth = 100 / $per_row;
$cellwidth .= "%";
for ( $x = 0; $x < count( $numbers ); $x++ ) {
$row[] = $numbers[$x];
if ( ( $x + 1 ) % $per_row == 0 ) {
$all[] = $row;
$row = NULL;
}
else if ( ! $numbers[$x + 1] ) {
$numbers[$x + 1] = "empty";
}
}
echo $per_row . " items per row: <br><br>\n";
echo "<table border=\"1\" width=\"400\"><tr>";
for ( $x = 0; $x < count( $all ); $x++) {
for ( $y = 0; $y < count( $all[$x] ); $y++ ) {
echo "<td align=\"center\" width=\"$cellwidth\">" . $all[$x][$y] . "</td>";
}
echo "</tr>\n<tr>";
}
echo "</tr></table>\n<br>\n";
echo "<form action=\"./numbers.php\" method=\"post\">\n" .
"<input type=\"text\" name=\"per_row\" size=\"2\">\n" .
"<input type=\"submit\" value=\"items per row\">\n</form>\n";
?>