A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > PHP > PHP Zebra Striping a Table Submit one!

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

20 Responses

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

  2. David says:

    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.

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

  4. bucabay says:

    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. Jack says:

    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. Artem says:

    Cant understand, how it works…

  7. iTechRoom says:

    Very handy and useful trick.

  8. Erwin says:

    what about using array?

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


    <tr class="">

  9. Erwin says:

    sorry, forgot the code wrapper


    <tr class="”>

  10. Erwin says:

    hmm still not working using pre or even code wrapper

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

  11. jennifer says:

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

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.