1

I wrote a simple while loop:

while($fetch = $stm->fetchAll()) {
    echo '<tr class=""'>;
    echo '<td>' . $fetch['name'] . '</td>';
    echo '</tr>';
}

How can I make the class="" alternate everytime so that every other row is white and every other row is grey? I already have the CSS class "greyRow" but don't know how to logically use it to make them alternate in PHP.

I'd assume I'd need a for loop, but how do I use it for what I'm trying to do?

Thanks.

0

3 Answers 3

2

A simple way would be to implement a variable to "count"

$odd_row = 1;
while($fetch = $stm->fetchAll()) {
    if ($odd_row == 0) 
        echo '<tr>';
    else
        echo '<tr class="greyRow">';
    echo '<td>' . $fetch['name'] . '</td>';
    echo '</tr>';
    $odd_row = !$odd_row;
}

But there are better ways, using strictly CSS.

Using CSS :even and :odd pseudo-classes with list items

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a counter variable if $counter % 2 == 0 (or !($counter % 2)) you're on an even numbered row. Otherwise it's odd.

$counter = 1;
while($fetch = $stm->fetchAll()) {
    echo '<tr class="', (!($counter % 2) ? 'even' : 'odd'), '">';
    echo '<td>' . $fetch['name'] . '</td>';
    echo '</tr>';
    $counter++;
}

You can also just try an nth-child CSS selector and avoid doing this in PHP at all. It's not cross browser, however. If you need to support IE < 8, you'll need to do the above.

Example:

#your-table tr:nth-child(odd) {
   // style odd rows differently
}

Comments

1

Here is my method:

while($fetch = $stm->fetchAll()) {

  if( !isset( $row_num ) ) $row_num = 1; // at first $row_num does not exist so create it and make uneven (start with 1)
  $row_class = (++$row_num % 2) ? 'even' : 'odd'; // then check whether $row_num is odd or even and assign it the corresponding class name

  echo '<tr class="'.$row_class.'">';
  echo '<td>' . $fetch['name'] . '</td>';
  echo '</tr>';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.