treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Applying Even/Odd Classes

Last updated on:

<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

View Comments

Comments

  1. Laurie
    Permalink to comment#

    FYI, the 2nd example should read:

    class="class"

  2. Laurie
    Permalink to comment#

    doh:
    class="class\"

  3. Permalink to comment#

    Easiest method I have ever seen, thank you!

  4. Permalink to comment#

    That was easy!

    Thanks~!

  5. Weldo
    Permalink to comment#

    Wow. That rocks! Thank you so much!

  6. ayesha

    thanku :) heaps :)

  7. It´s very Good

  8. Permalink to comment#

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

  10. for($i=1; $i<=10; $i++){

    if($i%2){ echo "class"; } else { echo "class"}

    }

    Simple example can be use in any loop even in wordpress.

  11. Jorge Santillan
    Permalink to comment#

    And… if you php.ini has enabled the directive “short open tag” then the snippet becomes shortest ever!! hehe

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

Leave a Comment

Use markdown or basic HTML and be nice.