Page 1 of 1

sorting odd's and even's

Posted: Wed Nov 07, 2007 10:46 pm
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'>"
}

Posted: Wed Nov 07, 2007 11:07 pm
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.

Posted: Thu Nov 08, 2007 8:47 am
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.

Posted: Thu Nov 08, 2007 10:01 am
by WaldoMonster
Bitwise and can also be used like: ($i & 1) ? 'odd' : 'even';

Posted: Sat Nov 10, 2007 4:56 pm
by califdon
Yeah! Nice compact coding, as long as you understand bitwise operators. :)