Website Design Westchester | Graphic Design New York | Online Marketing Westchester | SEO NY | Corporate Branding Westchester New York | Application Development NYC


How to alternate row colors in PHP

February 6th, 2010

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

StumbleUponLinkedInShare
© Black Rhino Solutions, Inc 2009-2012 All Rights Reserved | Terms & Conditions | Privacy Policy
Web Design Westchester

* Means Mandatory

Full Name * Project Budget

Services Needed:






Your Role/Title Project Timeline
Phone Number * When do we start?
Email Address * Project Description *
Company Name
Website URL

To check that your human please copy the image on the left
website design westchester