Simple PHP: Color every other row

December 28, 2007 10:43 pm admin PHP, Tutorial

Introducing PHP here on my blog and will start with a simple code to color every other row. Assume that you have a comment system, to make it easier to see when there is another comment you want to color every other row.

This can simply be done with:

$alternate = ($i++ & 1) ? "#fff" : "#eee";

The $i variable will be 0 by default and when you put that code in a while loop(for example), the $i variable will increase 1 every time. After “$i++” there is “& 1″, that will make your color variable($alternate) alternate between the both colors(#fff and #eee). In a working example it would look like this:

while( $row = mysql_fetch_array($query) )
{
	$alternate = ($i++ & 1) ? "#fff" : "#eee";
	echo "<div style='background:$alternate;'></div>";
}

And that’s almost everything, one thing to notice here is that the code above will leave you some ugly inline styles, so what you really should do is to switch those colors to classes, like this:

while( $row = mysql_fetch_array($query) )
{
	$alternate = ($i++ & 1) ? "color1" : "color2";
	echo "<div class='$alternate'></div>";
}

And define the two colors as background colors in your css file:

.color1 { background: #fff; }
.color2 { background: #eee; }

That’s it for me, hope you could follow and have a nice day!

Sprid denna post: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • StumbleUpon
  • Technorati

642 Visningar
VärdelösDåligGodkändBraImponerande (5 röster, medel: 3.4 av 5)
Loading ... Loading ...

« « Föregående: CSS Tips and Trix | Nästa: Ol start number » »

4 svar

[ Citera ] admin Säger:

Sorry for the crappy description(and my english as well), but it’s the technique that is important.




[ Citera ] Ante Säger:

.color1 and .color2 aren’t design-specific (which is good) but hardly semantic either.
.odd and .even are much better for naming alternative rows imo, but I’d skip all that back-end and rely on CSS using the :nth-child(odd/even) pseudo-class instead.




[ Citera ] admin Säger:

True, but in this case I wanted to concentrate the readers to the php part and how it should be applied. Thx for the pseudo-class tip!




[ Citera ] Olof G Säger:

Thanks for this dude, love it! :)




Lämna en kommentar

Du kan använda: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Att notera: Kommentarerna måste accepteras av admin innan dom publiseras.


Göm/Visa menyn