sorting odd's and even's

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
iknownothing
Forum Contributor
Posts: 337
Joined: Sun Dec 17, 2006 11:53 pm
Location: Sunshine Coast, Australia

sorting odd's and even's

Post by iknownothing »

Hey Guys,

I have a SELECT statement that pulls out all the data from a table. How would I code it so that all the rows with odd id numbers will show up with a different background color to those with even numbers.

eg.

Code: Select all

if (odd){ 
     echo "<tr class='this'>"
} 
else{ 
     echo "<tr class='that'>"
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$x % 2 is a fun, old expression used for this sort of thing.

If you're confused, search for "zebra striping" or variants thereof. I'm pretty sure I remember at least one thread linked from Useful Posts about this.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Post by califdon »

The math term for this operation is "modulus" or "mod". If you take any integer (say, 23) and divide it by another integer (say, 5), the modulus is the integer remainder (in this case, 3, since 4 times 5 = 20). So if you take a number modulus 2, it will always be either 0 or 1. If it's 0, it's even; if it's 1, it's odd.
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

Bitwise and can also be used like: ($i & 1) ? 'odd' : 'even';
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Post by califdon »

Yeah! Nice compact coding, as long as you understand bitwise operators. :)
Post Reply