Go to content Go to navigation & search

welcome to weekeat.com

Navigation

navigation

feeds

choose: rss / atom


Content

Generating alternating values in PHP

posted 5 August 2006

For PHP programmers, I’m sure you’ve done this many times – creating alternating table rows with different colors or divs, or… err… I’m sure you know what else.

Anyway, I was working on a simple project and needed to generate alternating colored rows. So, I started thinking about the fastest way of achieving this.

So, I did a little Googling and found lots of ways for achieving this, but none is simple enough. I then turned to a few open source projects and examine how various developers achieve the same result. In the end, I came across one ( Mambo CMS) that is really simple and efficient (I hope).

This is how it works:

PHP:
  1. // alternate.php
  2. $k = 0;
  3. for( $i=0; $i < 5; $i++ ) {
  4.     $k = 1 - $k;
  5.     print $k . "\n";
  6. }

Running the above script above on CLI will show the following:

me@mycomp:~$ php alternate.php me@mycomp:~$ 1 me@mycomp:~$ 1 me@mycomp:~$ 1

How cool is that? One simple line does it all. So, now you have a fast and efficient way of generating alternating values in your future projects!

 
Comment by: Ste Riley (Oct 17, 19:53)

I tend to use this approach:

echo ($i % 2) ? 1 : 0;

Although I’m not aware of the drawbacks of this method, can you point them out?

Comment by: Wee Keat (Oct 17, 20:09)

Hi Riley,

Thanks for sharing! I don’t see any drawbacks from your method. It looks just as simple, but I'm not sure about using modulo (I'm somehow afraid of them!).

Performance wise, not sure. Maybe I’ll run a benchmarking test when I have the time. :)

Got something to say?

  Textile Help