Page 1 of 1
using for loop to alternate 2 colors in table
Posted: Sat Dec 11, 2004 1:25 pm
by HormonX
Can anyone help with this. What i want to do is to alternate 2 different colors in table that will be displaying information from the database.
can i use for loop to that for me ?
Am sure you know what i mean but just in case
Row 1 - red
Row2 - blue
Row3 - red
Row4 blue
.. and so on.
Thank you.
Posted: Sat Dec 11, 2004 1:37 pm
by John Cartwright
Code: Select all
<?php
echo '<table>';
$x = 0;
while ($row = mysql_fetch_assoc($result))
{
$x++;
if ($x % 2 == 1
? $bg = '#000000'
: $bg = '#FFFFFF'
);
echo '<tr><td bgcolor="'.$bg.'">'.$row['rownamehere'].'</td></tr>';
}
echo '</table>';
?>
THis is generally how it is done.
Posted: Sat Dec 11, 2004 1:44 pm
by Selkirk
Code: Select all
for ($i=0; $i < 10; $i++) {
echo "Row $i - " . (( $i % 2) ? "odd" : "even") . "\n";
}
Posted: Sat Dec 11, 2004 3:13 pm
by ol4pr0
Same thing just a bit differant
Code: Select all
<?
$coloralternator = "";
while($row = mysql_fetch_assoc($result)) {
$color = ($coloralternator++ %2 ? "red" : "blue");
?>
<TR bgcolor="#<?echo $color;?>" #....ect
Posted: Sat Dec 11, 2004 3:30 pm
by rehfeld
and if you want to support more than 2 colors
Code: Select all
<?php
$colors = array(
'red',
'green',
'blue',
'yellow',
'grey',
);
$num_colors = count($colors);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$bgcolor = $colors[$i++ % $num_colors];
echo "$bgcolor<br>";
}
?>
Posted: Sat Dec 11, 2004 5:34 pm
by timvw
conclusion:
-use a counter which counts from 1 to number_of_colors and then starts at 1 again
- or be lazy, just add 1 all the time to your counter, and then use modulo function (%) to find out which color you are displaying now.
Posted: Sat Dec 11, 2004 9:49 pm
by pickle
Yet another way
Code: Select all
while($row = mysql_fetch_assoc($result))
{
$row_bool = !$row_bool;
$row_class = ($row_bool) ? 'light_row' : 'dark_row'
echo "<td class = '$row_class'>......";
}
Posted: Sat Dec 11, 2004 9:54 pm
by qads
Code: Select all
<?php
$color = ($color == "red") ? "blue" : "red";
?>
Posted: Mon Dec 13, 2004 5:27 am
by CoderGoblin
If you don't mind using javascript, two useful links... (some people may have it disabled)
http://www.alistapart.com/articles/tableruler/
http://www.alistapart.com/articles/zebratables/
Regards
Posted: Mon Dec 13, 2004 9:47 am
by LostOne
qads, thanks. I have been using Mod all this time......
