Practical Web Programming

Tuesday, December 30, 2008

PHP: How to Dynamically Alternate the Table Row Background Color

In PHP, making the <table> row background color alternate dynamically is relatively easy. The key here is PHP's modulo (%) operator. Using the % operator inside a loop construct, you can reference every other row in an HTML <table>. See the example below.

Create the CSS rules.
.alt-color-1{
background-color:red;
}

.alt-color-2{
background-color:green;
}


Create the PHP script.
<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";
for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0)
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>


Put it all together.
<html>
<head>
<title>Alternate Color in Table Rows</title>

<style>
.alt-color-1{
background-color:red;
}
.alt-color-2{
background-color:green;
}
</style>

</head>
<body>

<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";

for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0) //USE THE MODULO OPERATOR
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>

</body>
</html>


After executing the PHP script, here's what the webpage will look.

PHP: How to Dynamically Alternate the Table Row Background Color

0 comments:

Recent Post