Alternate table row colors dynamically with PHP?

  • Thread starter Thread starter Cathy V
  • Start date Start date
C

Cathy V

Guest
This is what i"m trying but it's not working. Thank you for helping.
<?
for ($i = 0; $i < 10; $i++)
{
if ($i % 2 == 0)
{
$bgcolor = '#FFFFFF';
}
else
{
$bgcolor ='#E5E5E5';
}
}
echo
"
<table width='200' border='2' cellspacing='0' cellpadding='0'>
<tr bgcolor='$bgcolor'>
<td>content</td>
<td>content</td>
</tr>

<tr bgcolor='$bgcolor'>
<td>content</td>
<td>content</td>
</tr>

<tr bgcolor='$bgcolor'>
<td>content</td>
<td>content</td>
</tr>
</table>

"
;
?>
 
You're generating the table AFTER you've run through the loop multiple times. This means every row will be set to the same colour. You need to output the rows within the loop itself.

Something like this:

echo "<table width='200' border='2' cellspacing='0' cellpadding='0'>"

for ($i = 0; $i < 10; $i++)
{
if ($i % 2 == 0)
{
$bgcolor = '#FFFFFF';
echo "<tr bgcolor='$bgcolor'>
<td>content</td>
<td>content</td>
</tr>"
}
else
{
$bgcolor ='#E5E5E5';
echo "<tr bgcolor='$bgcolor'>
<td>content</td>
<td>content</td>
</tr>"
}
}
echo "</table>"
 
Loop it all:
<?
echo "<table width='200' border='2' cellspacing='0' cellpadding='0'>";

for ($i = 0; $i < 10; $i++)
{
echo "<tr bgcolor='";
if ($i % 2 == 0)
{
echo '#FFFFFF';
}
else
{
echo '#E5E5E5';
}
echo "'>
<td>content</td>
<td>content</td>
</tr>";
}

echo "</table>";
?>
 
Back
Top