user1551496
user1551496

Reputation: 169

If else using for setting class

I want to set every first and second tr with a different class. With my code I only get "odd" on every tr. Does anyone knew what is wrong?

 $rowCount = 0;
 if ($rowCount++ % 2 == 1 ) :
     echo "<tr class='even'>";
 else:
     echo "<tr class='odd'>";
 endif;

Upvotes: 0

Views: 70

Answers (2)

TheMohanAhuja
TheMohanAhuja

Reputation: 1875

Your logic implementation is going in wrong direction

$rowCount = 0;//This was always initializing your count to 0

Resulting always odd class added

Change it to this:

for ($rowCount = 0;$rowCount<$total; $rowCount++) {
    if ($rowCount % 2 == 1 ) :
        echo "<tr class='even'>";
    else:
        echo "<tr class='odd'>";
    endif;
}

OR you can simply use ternary operator as

for ($rowCount=0; $rowCount<$total; $rowCount++) {
    echo "<tr class='".($rowCount % 2 == 0 )?'odd':'even'."'>";
}

Upvotes: 1

Luis Masuelli
Luis Masuelli

Reputation: 12333

try this one (keep the $rowCount setting outside the loop):

for($row = 0; $row < $rowTotal; $row++)
{
   echo "<tr class='".($row % 2 ? "even" : "odd")."'>";
}

Upvotes: 2

Related Questions