0

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;
2
  • 3
    Well from just that code, it looks like you are setting $rowCount = 0 every time. Can you provide a bit more information. Also, why wouldn't you just use a conditional operator? e.g. echo '<tr class="' . (($rowCount++ % 2) ? 'even' : 'odd') . '>' Commented Mar 27, 2014 at 15:15
  • I find out what i have done wrong. I put the $rowCount = 0; in the while. Commented Mar 27, 2014 at 15:54

2 Answers 2

2

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

for($row = 0; $row < $rowTotal; $row++)
{
   echo "<tr class='".($row % 2 ? "even" : "odd")."'>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

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'."'>";
}

1 Comment

the for loop has an error in your code. actually the error is in the loop body: remove the additional ++ (in the ternary-op expression), since having it twice will increment twice the number per iteration.

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.