note 63561 added to control-structures.while

From: Date: Thu, 23 Mar 2006 21:42:09 +0000
Subject: note 63561 added to control-structures.while
Groups: php.notes 
Request: Send a blank email to php-notes+get-106493@lists.php.net to get a copy of this message
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. ---- Server IP: 203.114.129.125 Probable Submitter: 203.110.28.82 ---- X-Spam-Status: No, hits=3.3 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER, HTML_MESSAGE autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/control-structures.while.php Edit -- http://master.php.net/note/edit/63561 Del: integrated -- http://master.php.net/note/delete/63561/integrated Del: useless -- http://master.php.net/note/delete/63561/useless Del: bad code -- http://master.php.net/note/delete/63561/bad+code Del: spam -- http://master.php.net/note/delete/63561/spam Del: non-english -- http://master.php.net/note/delete/63561/non-english Del: in docs -- http://master.php.net/note/delete/63561/in+docs Del: other reasons-- http://master.php.net/note/delete/63561 Reject -- http://master.php.net/note/reject/63561 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#106493) next »