Alternates - PHP test for Odd or Even

You want alternating backgrounds for posts down the page, or alternately styled table rows, or alternating anything - you need to test whether something is odd or even.


PHP has a number of ways of doing this, the two simplest are:

1. Modulus - the remainder

( $number % 2 )

If $number is odd, it will have a remainder when divided by 2 and so will return boolean true, equally when $number is even, there’s no remainder, this returns false.

You could use this like so:

$postClass = ((int) $postCount % 2 ) ? “oddColor” : “evenColor”;

The (int) type casting is just to cover everything…

2. Bitwise operation - the & operator

(Not && which is the and logic operator)

$a & $b - bits that are set in both $a and $b are set. If you not familiar with bitwise, it’s enough to know that

( $number & 1 ) will return true if $number is odd and false if even.

So it can be used in exactly the same way. It’s supposed to use less resource, apparently, so if you plan on printing more than 10,000 posts to one page, use this one.

Bookmark:
These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Google
  • Facebook
  • Furl
  • NewsVine
  • Reddit
  • StumbleUpon
  • Sphinn
  • Technorati

1 Comment

Pingbacks/Trackbacks

  1. Wp Wordpress » Blog Archive » Alternates - PHP test for Odd or Even

RSS feed for comments on this post. TrackBack URI

Leave a comment