3

I have a PHP loop that displays data for a particular posting on my website. What I want to do is dynamically assign either and even/odd CSS class for the number of row that is returned. For example,

first row returned - odd class
second row returned - even class
third row - odd class

This will allow me to assign different background colors to keep the data visually separate.

I should clarify - this data isn't being returned in a table.

 while ($row = mysql_fetch_assoc($result)) {

    echo "
    <div class=\"songContainer\" id=\"" . $row['trackid'] . "\">
3
  • What is your question? What have you tried so far? Please post some code. Please use the search function of the site (because this looks like a duplicate question). Commented Nov 18, 2011 at 3:10
  • Quicker to have a frontend jquery code like datatables.com - google jquery table display plugin. Commented Nov 18, 2011 at 3:10
  • 1
    possible duplicate of php: how to add odd/even loop in array Commented Nov 18, 2011 at 3:11

5 Answers 5

14

Depending on which browsers you have to target, you could just do that with CSS:

.mytable tr:nth-child(even) { background-color: #FFF; }
.mytable tr:nth-child(odd) { background-color: #EEE; }

You can even do more complex things with this pseudo-class: http://www.quirksmode.org/css/nthchild.html

If you really need PHP, use a modulo:

$i = 0;
foreach ($arr as $val) {
    if (0 == $i % 2) {
        // even
    }
    else {
        // odd
    }
    $i++;
}
Sign up to request clarification or add additional context in comments.

Comments

2

nth-child class is supported in CSS3 like this.

table tr:nth-child(even) td{

}

table tr:nth-child(odd) td{

}

But if you're to support older ones too, you have no choice but to generate class names by PHP.

Comments

1
$num_rows = 0;
$current_class = "";
while ($row = mysql_fetch_array($result)){
    $current_class = "class_odd";
    if($num_rows % 2 == 0){
        $current_class = "class_even";
    }

    $num_rows++;
}

Comments

0

Use this jQuery:

$("tr:nth-child(2n)").addClass("even")
  .prev().addClass("odd");

It selects every second tr element and adds an even class to it. Then it selects the previous tr element and adds an odd class to it.

Example.

Comments

0

When using php you can use this instead of modulo suggested by Pascal:

    $i = 0;
    foreach ($arr as $val) {
        if ( $i = 1 - $i ) {
            // even
        }
        else {
            // odd
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.