Generating alternating values in PHP
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:
- // alternate.php
- $k = 0;
- for( $i=0; $i < 5; $i++ ) {
- $k = 1 - $k;
- }
Running the above script above on CLI will show the following:
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!
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. :)
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?