Creating nice looking tables in PHP

This is a really old entry — I will no longer vouch for its sanity. :)

So, you want to make those nice, “business”-looking tables with alternating colors on the rows? Here’s how.

First, have a look at this example:

Name: City:
Ola Nordmann Oslo
Kari Hansen Arendal
Bjørn I. Skogen Elverum

It’s actually quite easy to make ‘em. Now, look at this set of functions:

<?php

$rowSwitch = 1;
    
function resetRows()
{
  GLOBAL $rowSwitch;
  $rowSwitch = 1;
}
    
function getRow()
{
  GLOBAL $rowSwitch;
  $return = "";
  if ($rowSwitch % 2)
    $return = "background=\"#CCCCCC;\"";
  else
    $return = "background=\"#EEEEEE;\"";
  $rowSwitch++;
  return $return;
}
    
function getLastRow()
{
  GLOBAL $rowSwitch;
  $rowSwitch--;
  return getRow();
}

?>

With these functions at hand, we can simply do something like this:

<?php

// Just to be sure
resetRows();
    
echo "<table>\n";
echo "<tr ".getRow()."><td><b>Name:/b></td>";
echo "<td><b>City:</b></td></tr>\n";
    
foreach ($employees as $employee)
{
  echo "<tr ".getRow()."><td>".$employee["name"]."</td>";
  echo "<td>".$employee["city"]."</td></tr>\n";
}
    
echo "</table>\n";

?>

Posted in Guides, PHP

Comments