Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating between even and odd in a while loop in PHP

Tags:

php

while-loop

I have been working on couple of lines of code but I can't seem to get it to work. Basically I want to alternate between even and odd table-styles via a while loop. What am I doing wrong?

Seems as though it only loops through the if() everytime.

Thanx!

<?php
    include 'connect.php';
    echo "<table id='hor-zebra'>";
    $i = 0;
    while($row = mysql_fetch_array($result))
    {
       if(i%2 == 0)
       {
          echo "<tr class='even'>";
          echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
          echo "</tr>";
       }
       
       else
       {
          echo "<tr>";
          echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
          echo "</tr>";
       }
       $i++;
    }
    echo "</table>";

    mysql_close($con);

  ?>
like image 271
Ismailp Avatar asked May 24 '11 15:05

Ismailp


3 Answers

You have a typo in your if condition. It should be:

   if($i%2 == 0)

You can also save a few keystrokes by just assigning the class name to a variable in the if and else blocks:

   if($i%2 == 0)
   {
      $class = 'even';
   }
   else
   {
      $class = 'odd';
   }

   echo "<tr class='$class'>";
   echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
   echo "</tr>";
like image 156
Emil Vikström Avatar answered Nov 08 '22 17:11

Emil Vikström


you can also use the css .nth-child property

   tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

As per W3 example

like image 25
Khurram Ijaz Avatar answered Nov 08 '22 17:11

Khurram Ijaz


CSS-Tricks has posted a very very elegant solution to this problem. It appears like super-reductionist C++ magic. Essentially they do this:

<div class="example-class<?php echo ($xyz++%2); ?>">

This works in any loop: for, foreach and while. Modifying the integer gives you larger step sizes, i.e. reset after 3, reset after 4 and so on.

CSS-Tricks final solution

like image 1
ledawg Avatar answered Nov 08 '22 19:11

ledawg