Neat PHP trick for alternate background display

Posted September 27th, 2010 in Tehnikalije by Metod

Many is the time we have to use alternate background for displaying some data. The usual solution to this problem would look something like:

  1. <?php
  2.     $i = 0;
  3.    
  4.     foreach($somedata as $data) {
  5.         if($i % 2 == 0)
  6.             // alternate
  7.         else
  8.             // normal
  9.  
  10.         $i++;
  11.     }
  12. ?>

Which in my opinion is somewhat a dirty solution. So I did a little research and found a bit neater solution:

  1. <?php
  2.     $even = 0;
  3.    
  4.     foreach($somedata as $data) {
  5.         if($even)
  6.             // alternate
  7.         else
  8.             // normal
  9.        
  10.         $even = (int)($even xor 1);
  11.     }
  12. ?>

It might even be a bit faster but I have not done any benchmarking.