NameSilo

The simple way to do alternate row colors

Spaceship
Watch
Impact
20
everytime ive looked about at alternate row colors seen some long code which just isnt nesacary imo

heres the easyway, 3 variables, 1 if statement which can be nested in an iffstament
but heres the code
PHP:
// the variables
$bgcolor="#c0c0c0";
$bgcolor1="#EFEFEF";
$bgcolor2="#c0c0c0"; // for one color leave this feild empty

// the if statment
if($bgcolor==$bgcolor1)
	{
		$bgcolor=$bgcolor2;
	}
	else
	{
		$bgcolor=$bgcolor1;
	}

heres the code in an example

PHP:
 echo "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\">";

$bgcolor="#c0c0c0";
$bgcolor1="#EFEFEF";
$bgcolor2="";
$i=0;
while($i < 30)
{
if($bgcolor==$bgcolor1)
    {
        $bgcolor=$bgcolor2;
    }
    else
    {
        $bgcolor=$bgcolor1;
    } 
    echo "<tr bgcolor=$bgcolor><td>background color is $bgcolor</td></tr>";
    $i++;
}

echo "</table>";

heres a demo
http://www.crooty.co.uk/scripts/alternaterows.php

it basically says if bgcolor equals bgcolor1 set bgcolor as bgcolor 2 and then it swaps it around and does it every time
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
You can also write that like below to save yourself from writing the same thing twice and save a little coding. The ternary operator comes in handy for code like that. :)
PHP:
echo "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\">"; 

$bgcolor1="#c0c0c0"; 
$bgcolor2="#EFEFEF"; 
$i=0; 

while($i < 30) {
    $bgcolor = ($i % 2) ? $bgcolor1 : $bgcolor2; 
    echo "<tr bgcolor=$bgcolor><td>background color is $bgcolor</td></tr>"; 
    $i++; 
     
}
echo "</table>";
 
0
•••
deadserious said:
You can also write that like below to save yourself from writing the same thing twice and save a little coding. The ternary operator comes in handy for code like that. :)
PHP:
echo "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\">"; 

$bgcolor1="#c0c0c0"; 
$bgcolor2="#EFEFEF"; 
$i=0; 

while($i < 30) {
    $bgcolor = ($i % 2) ? $bgcolor1 : $bgcolor2; 
    echo "<tr bgcolor=$bgcolor><td>background color is $bgcolor</td></tr>"; 
    $i++; 
     
}
echo "</table>";

when i saw the thread, i was going to post something like this. :) i agree, this is the easiest way here :)
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back