Jump to content

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

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.