
Question:
I have a table generated by a foreach
loop.
Before the loop, I create $iteration = 0
. At the beginning of the loop it increments $iteration
.
Then I do this:
if($iteration % 2 == 0) {
$greyRow = 'css for a grey row';
}
I've only three rows, at max, to test this with, but it seems that it greys the 2nd and 3rd row under the current rule, rather than only the second.
Answer1:Perhaps you also need to have an else
statement to set back to the other color on the odd rows. Not quite sure without seeing more of your implementation.
if ($iteration % 2 == 0) {
$css = 'css for a grey row';
} else {
$css = 'css for a white row';
}
Answer2:This following will add a grey
class for even rows.
echo '<tr', ($iteration & 1 ? ' class="grey"': ''), '>';
<h3>Note</h3>
This uses a <a href="http://php.net/manual/en/language.operators.bitwise.php" rel="nofollow">bitwise operator</a>. It's a micro-optimization but far more optimal than the modulus operator (although notoriously used in these cases).
Also, I would encourage you to utilize CSS classes for even and odd rows versus inline styles or just toggling a single class (i.e. grey
).
echo '<tr class="', ($iteration & 1 ? 'even': 'odd'), '">';
Answer3:I like to do this kind of thing..
<style type="text/css">
.odd td { background: #eee; }
</style>
<tr class="<?= ++$iteration % 2? 'odd' : 'even'; ?>">....</tr>