0

Basically, I'm trying to make a table where the color slightly changes for each row.

I'm going to do this by naming each even row class="even" and every odd row class="odd".

In my loop then, I need to figure out if the instance of the array is odd or even.

I can do almost do this by writing:

if (count($row)%2 == 0)  //while $row is an array from a mysql query
    {
    echo "<tr class='even'>";

if (count($row)%2 == 1)
    {
    echo "<tr class='odd'>";
    }

However writing count($row) gives me the count for the whole array, not the number of the instance which indicates where it falls in the whole array. Any ideas on how I could get the number of the instance within the array?

Thanks

3 Answers 3

3

Don't use PHP for this. Use CSS:

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
Sign up to request clarification or add additional context in comments.

5 Comments

... which still needs to be generated using PHP. Jeff's content is presumably not static, since he mentions a database query.
@Jared: His content can be dynamic, that doesn't mean he should use PHP for the style.
This answer doesn't solve his problem, which is a PHP one, not a CSS one. Besides, nobody said he wasn't using CSS.
According to quirksmode.org/css/contents.html#t38 nth-child is unsupported in quite some browsers (especially IE).
@JRL this css features is very nice -- much simpler than stupid class names - thanks
1

Try something like this:

$i = 0;
while ($i < count($row)) {
  if (($i % 2) == 0) {
    echo "<tr class='even'>";
  } else {
    echo "<tr class='odd'>";
  }
  $i++;
}

3 Comments

Dont forget to increment $i.
@Jared Ng: Your edit will not produce what you expect. You should increment at the end of the while body.
This should have no problems. Sorry, it's been a while since I've touched PHP.
1

You could use a counter:

$i = 0   
while($row=mysql_fetch_array($yourquery)) {
   if ($i % 2 == 0) {
      echo "<tr class='even'>";
   } else {
      echo "<tr class='odd'>";
   } 
   $i++;   
}     

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.