Skip to content

Instantly share code, notes, and snippets.

@cp6

cp6/table_func.php

Created Sep 24, 2020
Embed
What would you like to do?
PHP function for making HTML tables
<?php
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>");
}
//Usage:
$theads = ['Player', 'Score', 'Bonus'];
$rows = ['George', '44', '8', 'Ben', '39', '6', 'Tom', '41', '5'];
tableBuilder($theads, $rows);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.