Alternating row colours

Using a counter

The first approach will use a counter to keep track of the number of iterations and will choose the appropriate array entry depending on whether it is even or not.

$colour = array('#99CCFF', '#FFFFFF');

for($i = 0; $output = mysql_fetch_array($query); $i++)
   echo $colour[$i % 2].$output['title'];

The output from a database is used to control the number of loops and the counter ($i) is used to index into the array of colours.

NB: No curly brackets {} are not needed around the for loop because the code to be executed is only one statement. See php introduction.

Removing the modulus

The use of an array means that we do not need to keep a counter to keep track of the colour, we can simply cycle through the elements in the array using the internal pointer.

while ($output = mysql_fetch_array($query))
   echo ((next($colour)) ? current($colour) : reset($colour));

The conditional statement checks if the array pointer has reached the end and if so it goes back to the start, otherwise it moves to the next element.

A table example

Below is an example of this technique that changes the row colour of a table.

echo '<table>';
while ($output = mysql_fetch_array($query))
   echo '<tr><td style="background-color:'. ((next($colour) == true) ? current($colour) : reset($colour)).'">
        '.$output['title'].'</td></tr>';
echo '</table>';

Alternating div colours

This technique can be applied to various elements including the div tag.

while ($output = mysql_fetch_array($query))
   echo '<div style="background-color:'.((next($colour) == true) ? current($colour) : reset($colour)).'">
        '.$output['title'].'</div>';

Using lists

Lists can also have styles alternated.

echo '<ul>';
while ($output = mysql_fetch_array($query))
   echo '<li style="background-color:'.((next($colour) == true) ? current($colour) : reset($colour)).'">
        '.$output['title'].'</li>';
echo '</ul>';

Alternating with more colours

This technique is not limited to two colours but to as many as is needed.

$colour = array('#99CCFF', '#FFFFFF', '#0066CC', '#0000CC');
echo '<ul>';
while ($output = mysql_fetch_array($query))
   echo '<li style="background-color:'.((next($colour) == true) ? current($colour) : reset($colour)).'">
        '.$output['title'].'</li>';
echo '</ul>';

Downloads

Categories

Tags

Social