PHP: Show alternate colors between rows
Posted on August 27, 2008, under PHP,
Bookmark it
Hi,
In this tutorial we will show you how to show alternate colors between (table) rows. They are nice to use in a site’s design.
First let’s define each color:
<?php // Define colors here $color_one = '#FFFFFF'; $color_two = '#E6F2F7';
Let’s build our sample array.
$array = array('apple','pine','strawberry',
'pear','banana', 'cranberry','kiwifruit');
We will use a variable that will increment with each loop:
$i = 1; // starting value ?>
Let’s output our values in table rows:
<!-- Table with alternate colors --> <table width="100%" cellspacing="0">
How we will determine which color to show for each row?
While looping trough the array, we will check if the variable $i is an either an odd or an even number. We will determine this by checking if ($i / 2) results in an integer. If it is, then $i is even ($color_one) . Otherwise, it is odd ($color_two).
<?php
foreach($array as $value)
{
/*
Check if ($i / 2) is an integer and determine which color to show.
We will divide the number by 2
*/
$color = (is_int($i / 2)) ? $color_one : $color_two;
?>
<tr> <td bgcolor="<?=$color?>"><?=$value?></td> </tr>
<?php $i++; // Increment $i } ?>
</table>
Here’s the complete code:
<?php
// Define colors here
$color_one = '#FFFFFF';
$color_two = '#BBCCED';
$array = array('apple','pine','strawberry',
'pear','banana', 'cranberry','kiwifruit');
$i = 1;
?>
<!-- Table with alternate colors -->
<table width="100%" cellspacing="0">
<?php
foreach($array as $value)
{
/*
Check if ($i / 2) is an integer and determine which color to show.
We will divide the number by 2
*/
$color = (is_int($i / 2)) ? $color_one : $color_two;
?>
<tr>
<td bgcolor="<?=$color?>"><?=$value?></td>
</tr>
<?php
$i++; // Increment $i
}
?>
</table>
The output will look like this:

You can use this in any loop (for, foreach, while). Make sure you have a variable that is incrementing with each row so you can determine the alternate color.
- August 27, 2008
- article by Gabriel C.
- 3 comments
Related Posts
-
Add Some Life to Your Colors: ColoRotateat May 16, 2009
-
Extract Colors from Images and Make Color Schemes: ColorSuckrat August 9, 2009
-
Table Sorting, Filtering etc. from JavaScript Toolboxat December 24, 2008
-
Show random image(s) from a directoryat September 21, 2008 with 6 comments
-
Checking the beginning of a string (prefix)at August 30, 2008 with 1 comment


3 Replies to "PHP: Show alternate colors between rows"
January 2, 2009 at 12:43 AM
I see you broke the html code just to add the php to increment the variable $i.
Did you know you could just increment $i when your defining $color?
Like this:
$color = (is_int($i / 2)) ? $color_one : $color_two; $i++;
January 2, 2009 at 4:04 AM
Yes, I know. I usually put it before the ending } of the loop because there are many cases when I need to use it in more than one situation. Example:
December 20, 2009 at 11:30 PM
Nice work..