Often when writing something for the web, you’ll need to output data in a table (or, for CSS zealots, nicely formatted <div>’s). In order to improve readability, you might want to colour every second row differently. This is really easy:
$counter = 1;
while($counter < 10) {
//set bgcolor
$bgcol = ($counter % 2 == 1) ? "#ececec" : "#ffffff";
//write the output html
echo "
Your content goes here...
";
//increment the counter
$counter++;
}
The above code is merely to illustrate the idea behind alternating rows. I’ve used a very short conditional that checks if the current row is even or odd. Based on that result, it sets the background colour variable to either #ffffff or #ececec. Once the loop has run, the counter is incremented, and we start over.
By the way, the line:
$bgcol = ($counter % 2 == 1) ? "#ececec" : "#ffffff";
is equivalent to using:
if ($counter % 2 == 1) {
$bgcol ="#ececec";
}
else {
$bgcol = "#ffffff";
}
Some extensions to make this code better are things like inserting real data (from a call to a database), replacing the table code with <div>’s, replacing the bgcolour values with a particular style class, and writing to a string/file/etc instead of echoing the results. Another cool thing (if in a user-based environment) is to add a subsequent if statement that checks to see if the row being processed matched the currently logged on user – this way you can show a user that the row in question belongs to them by defining a third bg colour and highlighting it differently to the rest.
A slightly more real-world example of how the code may look is:
$sql = "SELECT id, name, surname FROM person";
$result = mysql_query($sql);
$counter = 1;
while($row = mysql_fetch_array($result)) {
//set class
$classname = ($counter % 2 == 1) ? "dark-div" : "light-div";
//write the output html
echo "
". $row['id'] ."
". $row['name'] ."
". $row['surname'] ."
";
//increment the counter
$counter++;
}
And in next week’s issue, how to assemble a nuclear bomb from ordinary household items!
[...] instead wrap this up in a function and return the results. Another easy modification would be to alternate the background colours, as shown in my previous [...]
Just to remove one more line you can increment $counter like so:
$classname = (++$counter % 2 == 1) ? “dark-div” : “light-div”;
And therefore remove the
$counter++;
Nice and simple thanks.
Thanks Mark – Good point.
($i++%2) works also.
I tied this on a sample table and all my return data comes out with each item in a column with no highlighting. Is there something a novice is missing on your example above?
With current advances in stem cell research, it won’t be long before we can find a permanent cure for Type 1 and Type 2 diabetes. ‘
I also like to make poems and read lots of books that is related to Poetry.~~~
i love poetry because it is a way of expressing my own feelings.,~`
poetry is the thing i like, i create poems during my spare time-.;