![]() |
|||||||||||||
| [ PHP Menu ] [ Home ] [ About this Site ] [ Contact Us ] [ Site Policies ] [ Tech Lab ] [ Computer Lab ] [ Playpen ] [ Who Is Marvin?? ] |
Alternating Table Row ColorsWhen building a table full of data, its often handy to make alternating rows appear in different colors for ease of readability. If your tables never change, you can do this manually quite easily. But if you expect to occasionally add rows to the table, it can be a real headache fixing up all the wrong-color rows that you create whenever you add something. This is easy to handle using PHP. The basic premise is to use PHP to count data rows, then dynamically create a html string to create a color for each row. In the example, a variable called $cnt is initialized to 0 at the beginning of each table. At the start of each table row, the variable is incremented, then checked to see if it is even or odd. If it is even, the table row is highlighted (either by application of a table bgcolor statement or by application of a CSS style). PHP's ternary conditional operator is used to quickly perform the evaluation. The general syntax for the ternary conditional operator is:
condition ? value-if-true : value-if-false ;
For example, the expression shown below
$people_at_party > 30 ? 'too many' : 'plenty'
evaluates to "too many" if there are thirty or more people at the party, and to "plenty" if there are fewer people there. Example
|
||||||||||||