Odd and Even Rows

Over at Code Snippets, kasperx shows one method for alternating a value between two states (for instance, to display ‘zebra stripe’ tables.)

Here’s his code:

for($i=0;$i<10;$i++)
{
  if($i % 2)
  {
   // I'm in an even row
  }else{
   // I'm in an odd row
  }
}

That’s great if you are using a for loop, or a while loop for a known range but doesn’t work so well if you are (for example) pulling in an unknown number of rows from a database.

In these circumstances, I use the following:

$o = isset($o) ? ($o+1) % 2 : 0;

Advertisements

Software developer by day, scale model builder and wargamer by night.

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: