jakebathman
8/14/2017 - 8:56 PM

Make a quick HTML table from a PHP array

Make a quick HTML table from a PHP array

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;
}