Black Rhino Blog | How to alternate row colors in PHP Web Design Westchester | Graphic Design New York | Black Rhino Solutions, Inc
Web Design, Graphic Design, Applcation Development, Logo Design, Writing Services, Social Networking, Content Management System, Corporate Branding, SEO, Website Maintenance in Westchester New York

web design client log in

Black Rhino Marketing - Rhino Room Blog - Web Design and Graphic Design Tips, Updates, News, & Help


How to alternate row colors in PHP

I’m not sure if there is an easier way to do this in PHP, but this is the easiest way that I found to alternate the color of rows in a table. First you want to set a variable to 0, I used the variable i in this example, but you can really use anything. Then you want to go and check if the variable can be divided by two. If it can then it’s even and you set the color to any color you want. Obviously if it cannot be divided by two then it is even and you set an else statement to set those another color. This will therefore set the even rows one color and the odd rows another. At the end of the while loop you want to add one to your variable (example: i+1).

See below for an example.

  1. <?php
  2. $i=0;
  3.  while($row = mysql_fetch_array($result))
  4.  {
  5.        if ($i%2)
  6.        {
  7.            $bg='999999';
  8.        }
  9.        else
  10.        {
  11.            $bg='666666';
  12.        }
  13.        $i=$i+1;
  14. }
  15. ?>

That’s basically it. My next article will be about how to display PHP code. I found it to be a little more difficult to do this so I think it will be good to

Tags: , ,

One Response to “How to alternate row colors in PHP”

  1. andyw Says:

    After reading you blog, Your blog is very useful for me .I bookmarked your blog!
    Wishes your valentine day to be joyful!

Leave a Reply



terms and conditions | privacy policy

© Black Rhino Solutions INC 2008-2010 All Rights Reserved