Jump to content

Displaying rows of data with an alternating colour sequence?


Recommended Posts

Hey guys,

just wondering when you display data in a table, how do you display every second result with a different colour background?

ie:

result 1.    grey
result 2.    light grey
result 3.    grey
result 4.    light grey
result 5.    grey

.. etc

cheers!
This can easily be accomplished using PHP in a while loop if you are getting data from a database with PHP. However if you are using plain old HTML then you have to code in manually or you can use javascript which will seek out your table rows and alternate the colors for each row one by one.
Very very very basic example but here it goes:

[code=php:0]
<?

//------------------------------Making some results------------------------------\\
$result[] = "Hi, my name is corbin";
$result[] = "This is row number 2";
$result[] = "Guess what?  Row 3!";
$result[] = "Row4";
$result[] = "5";
$result[] = "6";
$result[] = "7";
$result[] = "8";
$result[] = "9";
$result[] = "10";
//------------------------------End results------------------------------\\

$color1 = "#808080"; //gray
$color2 = "#CCCCCC"; //lightgray

$rnum = count($result); //count $result
$i = 0;
echo "<table>"; //create the table
while($i < $rnum) { //start outputting the rows
$color = $color1;
if($i % 2) { $color = $color2; } /*if $i equally divides by 2 (if its even) then make the background color the second color
the weird thing about modulus (the % operator) is that it returns true if there is a modulus (remainder)... so if it returns true $i is odd.
*/
echo "<tr>";
echo "<td bgcolor=\"{$color}\">"; //start a cell
echo $result[$i]; //echo the result
echo "</td>"; //close the cell
$i++;
}
echo "</table>"; //close the table...
?>
[/code]
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.