logo

Alternate row colour in PHP

logo

Over the past couple of months I’ve been developing a content management system to give myself something to aim for and achieve. What I do with the system is unknown, maybe I’ll start using it at work.

Anyway, I’ve been posting some stuff on here that I may find userful for other developers, whether they know how or not. I wanted to do some alternative row colour for some table results within the system and this is what I did.

Presuming you have a counter such as $i, try this:

$i = 0;
foreach($vars as $var) {
$i++;

if($i%2 == 0) { echo 'class="first"'; } else { echo 'class="second"'; }

On the first row it will add the class ‘first’ and on the second row it will add ‘second’. It will keep repeating this until the last row.

In simple english: The variable $i is 0 before the foreach loop, we check if the variable is divided by 2, we will see if it is odd or even. If it divides, the remainder will be 0, and the classes will echo.

Leave a Reply

logo
logo
© daparky.com 2011