motov.net

  • Increase font size
  • Default font size
  • Decrease font size
  • default color
  • black color
Home arrow Tutorials arrow PHP arrow Print normal and multi-dimensional array as a html table
Print normal and multi-dimensional array as a html table Print E-mail
Monday, 24 September 2007
<?php
function array2table($array, $recursive = false, $return = false, $null = '&nbsp;')
{
    // Sanity check
    if (empty($array) || !is_array($array)) {
        return false;
    }
 
    if (!isset($array[0]) || !is_array($array[0])) {
        $array = array($array);
    }
 
    // Start the table
    $table = "<table>\n";
 
    // The header
    $table .= "\t<tr>";
    // Take the keys from the first row as the headings
    foreach (array_keys($array[0]) as $heading) {
        $table .= '<th>' . $heading . '</th>';
    }
    $table .= "</tr>\n";
 
    // The body
    foreach ($array as $row) {
        $table .= "\t<tr>" ;
        foreach ($row as $cell) {
            $table .= '<td>';
 
            // Cast objects
            if (is_object($cell)) { $cell = (array) $cell; }
            
            if ($recursive === true && is_array($cell) && !empty($cell)) {
                // Recursive mode
                $table .= "\n" . array2table($cell, true, true) . "\n";
            } else {
                $table .= (strlen($cell) > 0) ?
                    htmlspecialchars((string) $cell) :
                    $null;
            }
 
            $table .= '</td>';
        }
 
        $table .= "</tr>\n";
    }
 
    // End the table
    $table .= '</table>';
 
    // Method of output
    if ($return === false) {
        echo $table;
    } else {
        return $table;
    }
}
?>
Last Updated ( Friday, 28 September 2007 )
 
< Prev   Next >

Proof of Verification

Login Form






Lost Password?
No account yet? Register

Instant Messaging

My status  bbh2k3
171-881-244

Let us know

Do you think our products are too expensive?
 

Syndicate