user547794
user547794

Reputation: 14511

PHP while loop, even/odd rows returned

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'] . "\">

Upvotes: 3

Views: 12720

Answers (5)

Bjoern Borg
Bjoern Borg

Reputation: 59

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

Upvotes: 0

Charlie Brown
Charlie Brown

Reputation: 144

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

Upvotes: 1

Purag
Purag

Reputation: 17061

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.

Upvotes: 0

Pascal
Pascal

Reputation: 16941

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

Upvotes: 14

Moe Sweet
Moe Sweet

Reputation: 3721

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.

Upvotes: 2

Related Questions