Change the css class of every second row with php

http://jaycodesign.co.nz/blog/wp-content/uploads/2009/04/alternatingrows.gif

If you need to find odd numbers in an array in php it’s very easy. You just use the “%” command. eg.

if ($num % 2) {
echo “$num is odd”;
} else {
echo “$num is even”;
}

I think what it basically does is divides the number by 2 and if it’s not a whole number it renders it returns it as odd.

Here’s how this code can be very tidy and useful:

The following code can be helpful if you are doing a php foreach repeater to produce a table and you want to use an alternating css class on every second row.

Step 1:
Place a $count outside your foreach loop.

$count=”0″;

Step 2:
Create your rows with the alternating css classes

echo “<tr class =’”;
$count++;
if ($count % 2) {
echo “rowclass1″; }
else {
echo “rowclass2″;
}
echo “‘>”;
echo “<td>Your row Content</td></tr>”;

That’s it, each row will have a different css class and it saves you having to do each row manually!

Table Rows ALternating

Tags:

Leave a Reply