How to give alternating table rows different background colors using PHP
Or you could just use CSS:
table tr:nth-child(odd) {
background-color: #ccc;
}
<?php
$x++;
$class = ($x%2 == 0)? 'whiteBackground': 'grayBackground';
echo "<tr class='$class'>";
?>
It basically checks to see if $x is divisible evenly by 2. If it is, it is even.
P.S. if you haven't seen that style of if else query, it is called a ternary operator.
Set a variable to true/false or a number and then back again during each iteration. Or use the modulus operator such as $i%2==0 in a while loop where $i is a number and use this condition in a ternary statement or something that sets the class value of the <tr>
Easiest way to alternate row colors in PHP/HTML?
$i = 0;
while ( $row = mysql_fetch_assoc($result) ) {
echo '<tr class="' . ( ( $i %2 == 0 ) ? 'oneValue' : 'anotherValue' ) . '"><td>' . $row['something'] . '</td></tr>';
$i++;
}