Alternating rows and differentiated colours

for a long time the standard way of having alternate rows of a table (or whatever) in different colours has been to use the modulus.

something like this

 
while($row = mysql_fetch_assoc($result)){ 
    $testCount++;
    $style = (($testCount % 2)==0) ? 'row_even' : 'row_odd';
    echo "<div class=\"$style\">some information</div>";
}

but this seems one step more than necessary and I typically use just a ternary statement with a simple equality comparison (as opposed to needing the more complex math of a modulus and an increment).

$style = '';
while ($row=mysql_fetch_assoc($result)){
    $style = ($style === 'row_even') ? 'row_odd': 'row_even';
    echo "<div class=\"$style\">some information</div>";
}

by way of example, this script (using an array as dummied database data) produces the output shown below.

echo <<<CSS
<style type="text/css">
.row_odd {background-color:green;}
.row_even {background-color:blue;}
.row {width: 100px;}
</style>
 
CSS;
$array = array ('apples','oranges', 'carrots', 'leeks'); //dummy data
 
$style = ''; //initiate the variable
foreach ($array as $item){
	$style = ($style === 'row_even') ? 'row_odd' : 'row_even';
	echo "<div class=\"row $class\">$item</div>\r\n";
}

output (apologies for colours): …

.row_odd {background-color:green;} .row_even {background-color:blue;} .row {width: 100px;}

CSS;
$array = array (‘apples’,’oranges’, ‘carrots’, ‘leeks’); //dummy data
$style = ”; //initiate the variable
foreach ($array as $item){
$style = ($style === ‘row_even’) ? ‘row_odd’ : ‘row_even’;
echo “

$item

\r\n”;
}
?>

2 Comments

DonaldAugust 30th, 2008 at 8:55 am

Would be good to show some examples of this code.
I’ve been looking at a lot of the code you write and can’t wait for the User Management code, but sometimes I find it hard to put it into practice. An example would make much more sense.

Thanks ;-)

JustinAugust 30th, 2008 at 1:15 pm

Donald – i’m not sure what you mean by an example? is the code snip above not enough?

i’ve add example output just in case that was what you meant.

for the user management code: get in quick and add your wish list to the post as a comment.

Leave a comment

Your comment