Monday, 17 November 2014

How to apply alternate background color for rows of an HTML table using PHP Script

In some cases you may want to apply alternate background color for each row of an HTML table. Using a simple script you can solve the problem. You can just apply one color for every odd row and apply another color for every even row. Check whether current row is even or odd by using a rowcount variable and check the result of rowcount mod 2  (ie. rowcount % 2) is 0 or not and change the value of background color attribute accordingly.

If rowcount % 2 is 0 then it is a even row and apply one color for that, other wise it is odd row and apply another color.

  $bgcolor = "#ffffff";
   if ($i % 2 == 0)
              $bgcolor = "#ECD23F";




You can see the PHP implementation of the above problem here.

alternatecolor.php
<html>
    <head>       
        <title>Alternate color for rows in HTML table</title>
    </head>
    <body>
       <table border=0 cellpadding=2 cellspacing=0>
           <tr bgcolor=#CDCAA9>
               <th>Sl. No</th>
               <th width="300">Item Name</th>
           </tr>
          
            <?php          
                for ($i=1;$i<=10;$i++){ 
                        $bgcolor = "#ffffff";
                        if ($i % 2 == 0)
                                $bgcolor = "#ECD23F";

                        echo "<tr bgcolor=". $bgcolor . ">";                   
                            echo "<td>$i</td>";
                            echo "<td>Item $i</td>";
                        echo "</tr>";              
                }           
            ?>

          
       </table>
    </body>
</html>




Following is the output of the above script


See also

How to apply alternate background color for rows of an HTML table using CSS




No comments:

Post a Comment