Code Snippet
PHP Zebra Striping a Table
Table row in a loop:
<!-- Before loop -->
<?php $c = 0; ?>
<!-- Start loop -->
<tr class="<?=($c++%2==1) ? 'odd' : 'even' ?>">
<!-- End loop -->
CSS:
.even { background-color:#FFF; }
.odd { background-color:#666; }
You can even replace “tr” with “div” and do it w/ classes!
The only problem in this example is that it will give a notice for the undefined variable $c.
What I usually do is first initialise the variable to 0 before the start of the loop. Then you won’t get the notice.
this code doesnt work.
sorry, i’m no good using the code tags..
i took out the ‘var’ before the $c = 0;
When I insert
this code, it renders it unuseable. Why would it work w/o but not with?php var $c = 0;The keyword “var” can only be used inside a class declaration.
$c = 0;I think you confused it with the “var” keyword in JavaScript which initializes a variable.
You can also use the bitwise & to get odd and even.
eg:
<?php echo $c++&1 ? 'odd' : 'even'; ?>
Your example also has the odd and even switched around. Odd numbers will have $c++%2==1, not even.
Thanks bucabay!
Please can someone help?
I put the code into the tr tag on this line and the whole page stops giving an error message with this line number. Also when I put the code into the line the remaining tags don’t work
echo " \n£ $investment\n";Thanks in anticipation
Cant understand, how it works…
Very handy and useful trick.
what about using array?
$class = array('even' => 'odd', 'odd' => 'even');
$curr = 'even';
<tr class="">
sorry, forgot the code wrapper
<tr class="”>
hmm still not working using pre or even code wrapper
anyway what i do is using $class[$curr] inside my loop
Can use this after the “While function”…
$bgcolor = ($bgcolor == “#ececec”) ? “#ffffff” : “#ececec”;
then…
print “