Recipe 8.8. Generating HTML Tables with Alternating Row Styles

8.8.1. Problem

You want to display a table of information with alternating rows having different visual appearance. For example, you want to have even-numbered rows in a table have a white background and odd-numbered rows have a gray background.

8.8.2. Solution

Switch back and forth between two CSS styles as you generate the HTML for the table. Example 8-16 uses this technique with data retrieved from a database.

Generating an HTML table with alternating row styles

<style type="text/css"> .even-row {     background: white; } .odd-row {     background: gray; } </style> <table> <tr><th>Quantity</th><th>Ingredient</th></tr> <?php $styles = array('even-row','odd-row'); $db = new PDO('sqlite:altrow.db'); foreach ($db->query('SELECT quantity, ingredient FROM ingredients') as $i => $row) { ?> <tr >   <td><?php echo htmlentities($row['quantity']) ?></td>   <td><?php echo htmlentities($row['ingredient']) ?></td></tr> <?php } ?> </table>

8.8.3. Discussion

The key to the concise code in Example 8-16 is the array of CSS class names in $styles and the use of %, PHP's "remainder" operator. The remainder operator returns the remainder after dividing two numbers. The remainder when dividing something by two (in this case, the row number in the result set'$i) is either 0 or 1. This provides a handy way to alternate between the first and second elements of the $styles array.

8.8.4. See Also

Documentation on PHP's arithmetic operators at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: