PHP Tips: Alternate table row background

14 January 2012

Disclaimer
I use images to share code, not to be a pain in the arse, but because I don't have the option of bbCode on my site.
I also choose to use an image to share result to avoid having my own CSS interfere with the style.

 

To make table rows alternate their background is really simple, when you know how to. The one thing that does the trick is the modulus operator, %, together with an if-statement.

What modulus does is it divides the values and return the remainder. In this case, modulus will always be 0.5 whenever the row count is an odd number.
1 % 2 = 0.5
2 % 2 = 0
3 % 2 = 0.5

Start with a row counter and set it to value 1. Echo the start tag of your table. Then create your loop of choice. I use a simple for-loop in this demonstration. Within the loop, add an if-statement that compares the modulus of the row counter to 0. It doesn't matter if you use 'different from' ( != ) or 'equal to' ( == ) as long as you keep track of your rows and what background colour you want them to have.
if($i % 2 != 0)

Next, initialize a variable and add an RGB colour code as its value, including the "ladder", #.
$rowcolour = '#8FBC8F';

Add an else-statement with the same variable name, but make sure you initialize it with a different value. Otherwise you'll have the same background colour on every row. Not so neat. You can choose to not have a second row colour. What happens then is that the background colour of your website shines through. I use the following colour code for this demonstration:
$rowcolour = '#006400';

Now to the fun part. Echo a full table row and add bgcolor="" within the tr-tag. Within the quotation marks, use concatenation to add the variable holding the RGB value. Note: I use commas for concatenation but fullstops works as well (it saves a space per comma!).
bgcolor="', $rowcolour ,'"

End the block with a $i++; to make sure your counter increase with every loop. Lastly, echo the end table tag, outside the loop.

 

The full code

code example: alternate row colour

 

The result

code example: alternate row colour table

 

A second tip

If you plan on having more than one table on each page, use constants (opens in new tab). It will make things a bit easier when replacing colours. All you need to do is follow the steps of initializing constants as described on the constant page, and then add the following code to the if-else blocks:
$rowColour = constant('self::NAMEOFCONSTANT');