PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » PHP » PHP Zebra Striping a Table

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; }

Subscribe to The Thread

  1. You can even replace “tr” with “div” and do it w/ classes!

  2. 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;

  3. When I insert this code, it renders it unuseable. Why would it work w/o but not with?

  4. 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.

  5. 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

  6. Cant understand, how it works…

  7. Very handy and useful trick.

  8. what about using array?

    $class = array('even' => 'odd', 'odd' => 'even');
    $curr = 'even';


    <tr class="">

  9. sorry, forgot the code wrapper


    <tr class="”>

  10. hmm still not working using pre or even code wrapper

    anyway what i do is using $class[$curr] inside my loop

  11. jennifer

    Can use this after the “While function”…
    $bgcolor = ($bgcolor == “#ececec”) ? “#ffffff” : “#ececec”;
    then…
    print “

  12. bucabay, your code works!

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~