PHP - help in coding an echo instruction to create any other string of different background colors

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

I have the following PHP code that prints echoes and instructions:

$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 help when EVERY OTHER Row ($ row) has a different COLOR, but I don’t know how to do this programmatically using the echo instruction. Thus, it will 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 the help / contribution.

+4
source share
2 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 should be the class names of your alternate colors.

+5
source

CSS

http://www.w3.org/Style/Examples/007/evenodd - this cannot be done using CSS, because support for the nth-child property is not very good so far.

Javascript

http://api.jquery.com/odd-selector/ - The task with the jQuery library in JavaScript is quite simple. The disadvantage is that the colors may be a little late, and the user may notice that (a disadvantage in terms of MY).

Php

@Sarfraz introduced an easy way to do coloring using PHP.

Conclusion

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

+1
source

All Articles