How to Alternate Row Colors in CSS With PHP

By default, tables use one consistent background color for each row. Tables with large amounts of data and many rows might appear difficult to read because of this. Using a combination of classes in a CSS file and PHP scripting, you can alternate row colors in a table. You will use a loop to cycle through each row, regardless of how many you have in the table. You may use data for table rows from any source, including an array variable or records taken from a database.

Instructions

    • 1

      Open the CSS file. Type the following to define two classes:

      .row1 { background-color: #FFFFFF; }

      .row2 { background-color: #B0B0B0; }

      Any rows that use the "row1" class have a white background, and any rows that use "row2" have a light gray background.

    • 2

      Open the HTML file. Type the following to create a new table in HTML:

      <table>

      <tr>

      <th>Data</th>

      </tr>

    • 3

      Type the following to open a PHP tag and get the information you will use to populate the table:

      <?php

      $myArray = array("Item 1", "Item 2", "Item 3", "Item 4");

      $i = 0;

      The "$i" variable acts as a counter to alternate rows. Substitute "$myArray" with the actual data you need, such as rows from a database.

    • 4

      Type the following to alternate row colors in the table, then close the PHP and table tags:

      foreach ($myArray as $data) {

      if ($i % 2 == 1) {

      echo "<tr class=\"row1\">\n<td>" . $data . "</td>\n</tr>\n";

      } else {

      echo "<tr class=\"row2\">\n<td>" . $data . "</td>\n</tr>\n";

      }

      $i++;

      }

      ?>

      </table>

      The "if" function performs a "mod" calculation on the "$i" counter variable. When the result is one, the "row1" class with the white row color is applied to the row. When the result is zero, the "row2" class with the light gray color is applied to the row. The counter variable then increases by one, and the function repeats until every record from the $myArray variable is loaded into the table.

    • 5

      Save the HTML and CSS files and upload them to your Web server.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured