note 63561 deleted from control-structures.while by philip
| From: | philip@php.net | Date: | Thu, 27 Apr 2006 15:51:08 +0000 |
| Subject: | note 63561 deleted from control-structures.while by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-109862@lists.php.net to get a copy of this message | ||
Note Submitter: wbryson at gmail dot com
----
A more maintainable way to do alternate line colours:
<?php
$array = array('ex1','ex2','ex3','ex4','ex5');
print '<table width="90%" border="0" cellpadding="3"
cellspacing="1" align="center">';
$index = 0;
while ($index < count($array)) {
$color = $index % 2 ? '#EEEEEE' : '#CCCCCC';
print '<tr><td bgcolor="'.$color.'" style="font: 10px
verdana;">' . $array[$index] . '</td></tr>';
$index++;
}
print '</table>';
?>
An even better way to do this is via selecting alternate CSS classes, which is even simpler - but
that should come under a general discussion of good design rather than specific implementations of a
while loop.
For those not familiar with the ?: shorthand syntax, the format is:
$answer = $test ? $return_if_true : $return_if_false;
Which is equivalent to:
if ($test) $answer = $return_if_true; else $answer = return_if_false;
There is a good reason to go with $index++ instead of the current($array), next($array) method - if
false is an element in the array, current($array) will be false, and execution will stop. This is
probably undesirable behaviour - hence the use of an array index instead.