Code Snippet

Home » Code Snippets » PHP » Applying Even/Odd Classes

Applying Even/Odd Classes

<div class="example-class<?php echo ($xyz++%2); ?>">

Used inside a loop, class names would be named .example-class0 and .example-class1 alternating. Increasing the "2" number allows you to increment in thirds or fourths or whatever you need:

class="class<?php echo ($xyz++%3); ?>"

Classes: class0 class1 class2 class0 class1 class2

Change number to 4, this is the result: class0 class1 class2 class3 class0 class1 class2 class3

Subscribe to The Thread

  1. Laurie

    FYI, the 2nd example should read:

    class="class"

  2. Laurie

    doh:
    class="class\"

    • Laurie

      ok I give up. Just add 3 instead of 2 :P

  3. Easiest method I have ever seen, thank you!

  4. That was easy!

    Thanks~!

  5. Weldo

    Wow. That rocks! Thank you so much!

  6. ayesha

    thanku :) heaps :)

  7. It´s very Good

  8. Awesome,
    The easiest one so far. So we do not have to use the old

    
    $count = 1;
    if($count % 2 == 0) {
    ....
    }  else {
    ....
    }
    

    one…. Saves time :)

  9. what about this technique, i think its much faster then taking decision on if statement.

    $class = ($class==’class1′) ? “class2″ : “class1″ ;

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 ~