-
-
Save phillipwilhelm/8fdfad6e27d2830b476f38e2e2b6aeed to your computer and use it in GitHub Desktop.
Make a quick HTML table from a PHP array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function arrayToTable(array $values, array $headers = []) | |
{ | |
$options = [ | |
'tableStyle' => 'border: 1px solid black;border-collapse: collapse;', | |
'thStyle' => 'border: 1px solid black;padding: 5px 7px;text-align: center;', | |
'tdStyle' => 'border: 1px solid black;padding: 5px 7px;text-align: center;', | |
]; | |
$th = "<th style='" . $options['thStyle'] . "'>"; | |
$td = "<td style='" . $options['tdStyle'] . "'>"; | |
$html = "<table style='" . $options['tableStyle'] . "'>"; | |
if (!empty($headers)) { | |
if (count($headers) != count($values[0])) { | |
return null; | |
} | |
$html .= "<thead><tr>"; | |
foreach ($headers as $header) { | |
$html .= $th . $header . "</th>"; | |
} | |
$html .= "</tr></thead>"; | |
} | |
foreach ($values as $value) { | |
$html .= "<tr>"; | |
foreach ($value as $v) { | |
$html .= "{$td}{$v}</td>"; | |
} | |
$html .= "</tr>"; | |
} | |
$html .= "</table"; | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment