Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

alternating table row colors

Status
Not open for further replies.

MJB3K

Programmer
Jul 16, 2004
524
GB
Hi, how would you go about making alternate row colors like on this website??

any ideas??


Regards,

Martin

Gaming Help And Info:
 
try this code snippet: ($line must be an array)

Code:
<table>
<?
$color="#FFFFFF";
foreach ($line as $c)) {  
  if ($color=="#FFFFFF") {  // Alternate background color for readability
	$color="#CCCCCC";
  } else {
	$color="#FFFFFF";
  }
  echo "<tr bgcolor=$color>";
  echo "<td>$c</td>";
  echo "</tr>
}
?>
</table>

 
you have to set up $line yourself...
example:
$result=mysql_query("SELECT * FROM sometable");
$line=mysql_fetch_array($result);

-or-
$line[]="row 1 text";
$line[]="row 2 text";
...
$line[]="row n text";

then when you hit the foreach($line as $c), the $c variable becomes the value of the current $line and loops until there are no more $lines

 
Or:

Code:
// array for colors.. ("unlimited")
color[0] = "#FFFFFF";
color[1] = "#CCCCCC";
color[2] = "#B5B5FF";
$i = -1; // must be -1, so it will start at 0

echo "<table>";

Code:
// switch color
if ($i < count($color)) // if $i is lss than number of colors
  {
    $i++; // add one to $i
  }
else // oops, $i must be the same as number of colors
  {
    $i = -1; // restart $i
  }

echo "<tr bgcolor=\"{$color['$i']}\"><td>test</td></tr>";

Code:
echo "</table>";

ps. code is not tested, but in my mind it works perfect.

Olav Alexander Mjelde
Admin & Webmaster
 
ps. my way might be easier if you want the users to be able to choose design.. Then you can gather the array from a mysql table, quick, dirty and simple.

It will work almost as a smiley script, only no replacing whatsoever, it's actually easier.

the above code looks very good though, just so it's said.

Olav Alexander Mjelde
Admin & Webmaster
 
Sorry for this "flooding" on my behalf, but I forgot to mention:

The code chunk in the middle should be inside your recordset loop, while the others should be outside.

I guess it's obvious, but I just thought it would be worth mentioning.

The first code-chunk above the recordset loop, the second inside, the last (and third) below the recordset loop.

Olav Alexander Mjelde
Admin & Webmaster
 
Use the modulus operator

Code:
$array = array('data', 'data', 'data', 'data');

foreach ($array as $k => $v) {
 if ($k % 2 == 0) {
  echo 'class1<br>';
 } else {
  echo 'class2<br>';
 }
}

HTH

[smurf]
01101000011000010110010001110011
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top