derekbelcher Posted April 24, 2009 Share Posted April 24, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/155515-alternating-row-color-in-a-table-display/ Share on other sites More sharing options...
premiso Posted April 24, 2009 Share Posted April 24, 2009 $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. Quote Link to comment https://forums.phpfreaks.com/topic/155515-alternating-row-color-in-a-table-display/#findComment-818351 Share on other sites More sharing options...
derekbelcher Posted April 24, 2009 Author Share Posted April 24, 2009 Thanks so much. Very cool about the ? and :. I have seen that in other codes that I have worked with, but didn't know what they did. Thanks for the explanation. Quote Link to comment https://forums.phpfreaks.com/topic/155515-alternating-row-color-in-a-table-display/#findComment-818424 Share on other sites More sharing options...
Psycho Posted April 24, 2009 Share Posted April 24, 2009 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'; Quote Link to comment https://forums.phpfreaks.com/topic/155515-alternating-row-color-in-a-table-display/#findComment-818432 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.