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.










