| changing table bgcolor in a foreach loop
|
ahmed24

msg:4040998 | 10:25 pm on Dec 10, 2009 (gmt 0) | i have the following foreach loop that echos every row as bgcolor of #cccccc. Can anyone tell me how i can switch between two colors? so that the first row is #cccccc then the 2nd is #ffffff and the 3rd is back to #cccccc and so on? foreach($data as $key => $val){ echo "<tr>"; echo "<td bgcolor='#cccccc'>".$data[$key]['NAME']."</td>"; echo "</tr>"; } thanks
|
CyBerAliEn

msg:4041020 | 10:53 pm on Dec 10, 2009 (gmt 0) | Ah... I hate doing this. It sounds so easy! But it requires so much extra code for something so simple. <?php $color0 = "#CCCCCC"; $color1 = "#FFFFFF"; $i = 0; foreach($data as $key => $val) { $useColor = ($i%2); $thisColor = "color{$useColor}": $thisColor = $$thisColor; echo "<tr>"; echo "<td style=\"background-color:{$thisColor};\">".$data[$key]['NAME']."</td>"; echo "</tr>"; $i++; } ?>
Not tested, but it should work. How does it work? Specify the colors you want to use first (color0 is the first one used; then color1; then it repeats & alternates). You also have to setup an incrementing counter ($i). Each time the loop completes, this counter increases by 1. Inside the loop, it performs the operation ($i%2). This is mathematically: ($i)mod(2) [modulus operator]. What this does, is every loop, this operation will output: 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, etc (it continually alternates from 0 to 1, 1 to 0). It then uses some PHP variable manipulation to grab the corresponding color and inset it into the table output.
|
dreamcatcher

msg:4041077 | 12:53 am on Dec 11, 2009 (gmt 0) | You don`t need so much code CyBerAliEn, a simple ternary operator will suffice. $i=0; foreach($data as $key => $val){ echo "<tr>"; echo "<td bgcolor='#".(++$i%2==0 ? 'ffffff' : 'cccccc')."'>".$data[$key]['NAME']."</td>"; echo "</tr>"; } |
| dc
|
rocknbil

msg:4041516 | 5:57 pm on Dec 11, 2009 (gmt 0) | As always, TMTOWTDI. :-) Also I like to store in a variable as I go, then output once, to avoid the "half rendered" pages on a slow connection or server .This takes up a little more memory but overall, seems to render better. It also makes conditionals easier, examine: // Use CSS instead! $lightBG = 'light-bg-class'; $grayBG = 'dark-bg-class'; $out_table=NULL; foreach($data as $key => $val){ // Swap if you want white first row $thisBG=($thisBG==$lightBG)?$grayBG:$lightBG; $out_table .= '<tr><td class="' . $thisBG . '>' . $data[$key]['NAME'] . '</td></tr>'; } if ($out_table) { echo ' <table width="50%" align="center">' . $out_table . </table> '; } else { echo '<p>No data found</p>'; }
|
|
|