Jump to content

Alternating row color in a table display


derekbelcher

Recommended Posts

I display a table with the following code:

 

while($row = mysql_fetch_array($result))

{

echo "<tr>";

echo "<td><div align='center'>" . $row['unit'] . "</td>";

echo "<td><div align='center'>" . $row['name'] . "</td>";

echo "<td><div align='center'>" . $row['rank'] . "</td>";

echo "<td><div align='center'><a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>";

echo "</tr>";

}

echo "</table>";

 

How (or what code) do I use to alternate each row background color?  thanks

$i=0;
while($row = mysql_fetch_array($result)) {
   $color = (($i % 2) == 0)?"red":"blue";
   echo "<tr bgcolor={$color}>";
   echo "<td><div align='center'>" . $row['unit'] . "</td>";
   echo "<td><div align='center'>" . $row['name'] . "</td>";
   echo "<td><div align='center'>" . $row['rank'] . "</td>";
   echo "<td><div align='center'><a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>";
   echo "</tr>";
   $i++;
}
echo "</table>";

 

The ? and : is the ternary operator (shortened if/else). The % is the modulus operator. In case you want to read more up on them and how they work.

You should mark the topic as solved.

 

Also, since I love compact code I will offer a couple modifications to what Permiso provided.

 

1. Increment the counter in the comparison, then you don't need the $i++; at the end.

$color = (($i % 2) == 0)?"red":"blue";

 

2. Even better, don't use the counter at all

$color = ($color != 'red') ? 'red' : 'blue';

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.