PHP - help coding echo statement to create every other line of different background colors

I am creating a table (stats_1) dynamically and would like to have each row of different background color. So far, all the lines have the same background color.

I have the following php code that prints echoes out and statements:

$keys = array('Col1', 'Col2','Col3','Col4','Col5','Col6','Col7');
echo '<table id="stats_1"><tr>';            
foreach ($keys as $column)
   echo '<th>' . $column . '</th>';
    echo '</tr>';

foreach ($data as $row){                        
   echo '<tr class="alt">';                     
     foreach ($keys as $column)
        if (isset($row[$column])){              
          echo '<td>' . $row[$column];
          } else {
          echo '<td>' . '' . '</td>';
        }
}
echo '</table>';

I need some help making EVERY OTHER ROW ($row) have a different COLOR, but don't know how to do that programmatically with the echo statement. So, it would alternate printing between:

echo '<tr class="alt">';  or   echo '<tr>';

I define that in a class:

#stats_1 tr.alt td
{
color:#000000;                  
background-color:#E0E0FF;       
}

THanks for your help/input.

Answers


Try:

$counter = 0;
foreach ($data as $row){
  $counter++;

  $class = $counter % 2 === 0 ? 'foo' : 'bar';
  echo '<tr class="' . $class . '">';

  // more code....

Where foo and bar are supposed to be the class names of your alternate colors.


CSS

http://www.w3.org/Style/Examples/007/evenodd - it cannot be done simply via CSS because support of nth-child property is not very good so far.

JavaScript

http://api.jquery.com/odd-selector/ - The task is quite easy with jQuery library in JavaScript. The disadvantage is that the colors may appear a little bit late and user may notice that (a disadvantage from MY perspective).

PHP

@Sarfraz presented a simple way how to accomplish the coloring with PHP.

Conclusion

PHP seems best bet until the CSS property nth-child is implemented in major browsers.


Need Your Help

How do I fully clean my project?

android c compilation

I have fixed an error in my code, but every time I call ndk-build the same error is STILL there. I have called ndk-build clean fifteen times at least, but I have had no luck. I have gone into my pr...