I have been working on couple of lines of code but I can't seem to get it to work. Basically I want to alternate between even and odd table-styles via a while loop. What am I doing wrong?
Seems as though it only loops through the if() everytime.
Thanx!
<?php
include 'connect.php';
echo "<table id='hor-zebra'>";
$i = 0;
while($row = mysql_fetch_array($result))
{
if(i%2 == 0)
{
echo "<tr class='even'>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
$i++;
}
echo "</table>";
mysql_close($con);
?>
You have a typo in your if
condition. It should be:
if($i%2 == 0)
You can also save a few keystrokes by just assigning the class name to a variable in the if and else blocks:
if($i%2 == 0)
{
$class = 'even';
}
else
{
$class = 'odd';
}
echo "<tr class='$class'>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
you can also use the css .nth-child property
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
As per W3 example
CSS-Tricks has posted a very very elegant solution to this problem. It appears like super-reductionist C++ magic. Essentially they do this:
<div class="example-class<?php echo ($xyz++%2); ?>">
This works in any loop: for, foreach and while. Modifying the integer gives you larger step sizes, i.e. reset after 3, reset after 4 and so on.
CSS-Tricks final solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With