November 3, 2011

alternating row colors

Question by meandme

I am looking for a solution to use the alternating colors row design in my table which is from a csv.

my code:

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr class='odds'>";
        foreach ($line as $cell) {
                      echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>n";
}
fclose($f);
echo "n</table>";
?>

so how can i have the tr class to alternate from odds and even?
thanks

Answer by OptimusCrime

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
$i = 0;
while (($line = fgetcsv($f)) !== false) {
    echo "<tr style='background-color: ".(($i%2)?'green':'blue').";'>";
    foreach ($line as $cell) {
        echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>n";
    $i++;
}
fclose($f);
echo "n</table>";
?>

Or you could assign a class just the same way and style it using css. This is much better practice.

Answer by Starx

I will give you a better but much simpler solution, through CSS. First of all uniquely identify your table, i will show you a more general option.

table tr { backgroun: #ddd; }
table tr:nth-child(2n) { background: #ccc; } 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!