A PHP function to help reduce the load of duplicate code when producing HTML tables.
This works by looping through an array for the thead (columns <–>) and then the td content (rows). By getting a count of how many columns there are and then counting each loop through the td data as to know when to implement a new row.
In this format, it is easy to use with a return from a database query as an array.
The function:
function outputString(string $string) { echo $string; } function tableBuilder(array $theads, array $data, string $table_class = 'table', string $thead_class = '') { (empty($table_class)) ? $tbl = "" : $tbl = " class='$table_class'"; (empty($thead_class)) ? $th = "" : $th = " class='$thead_class'"; outputString("<table$tbl>"); outputString("<thead$th><tr>"); foreach ($theads as $column) { outputString("<th>$column</th>"); } outputString("</tr></thead><tbody>"); $columns = count($theads); $col_count = 0; foreach ($data as $content) { if (($col_count % $columns) === 0) { outputString("<tr>"); } $col_count++; outputString("<td>$content</td>"); if (($col_count % $columns) === 0) { outputString("</tr>"); } } outputString("</tbody></table>"); }
Calling:
$theads = ['Player', 'Score', 'Bonus']; $rows = ['George', '44', '8', 'Ben', '39', '6', 'Tom', '41', '5']; tableBuilder($theads, $rows);
Raw output:
<table class='table'> <thead> <tr> <th>Player</th> <th>Score</th> <th>Bonus</th> </tr> </thead> <tbody> <tr> <td>George</td> <td>44</td> <td>8</td> </tr> <tr> <td>Ben</td> <td>39</td> <td>6</td> </tr> <tr> <td>Tom</td> <td>41</td> <td>5</td> </tr> </tbody> </table>