tags:

views:

39

answers:

5
for($i=0;$i<$num;$i++) {
  if($i==even) $hilite="hilite";
  dothing($i,$hilite);
}

This is basically what I want to accomplish. What is the most efficient way to determine if $i is even? I know I could check if half == mod 2 ... but that seems a little excessive on the calculations? Is there a simpler way?

A: 

Change the i++ in the loop statement to i+=2, so that you only examine even values of i?

burningstar4
+2  A: 

if ($i % 2 == 0)

praksant
+1  A: 

It doesn't get any simpler than $i % 2 == 0. Period.

delnan
If you mod a number by 2, the result will NEVER be 2. It will always be (assuming $i isn't negative to begin with) either 0 or 1. It should read `$i % 2 == 0`.
sigint
Ouch, silly typo. Of course you're right.
delnan
@delnan Oh yeah, that's always a fun typo to have to debug...
sigint
A: 

Typically, a number is odd if it's LSB (Least Significant Bit) is set. You can check the state of this bit by using the bitwise AND operator:

if($testvar & 1){
  // $testvar is odd
}else{
 // $testvar is even
}

In your code above, a more efficient way would be to have $i increment by 2 in every loop (assuming you can ignore odd-values):

for($i=0;$i<$num;$i+=2){
  // $i will always be even!
}
sigint
+1  A: 

The already mentioned % 2 syntax is most used, and most readable for other programmers. If you really want to avoid an 'overhead' of calculations:

for($i = 0, $even = true; $i < $num; $i++, $even =! $even) {
  if($even) $hilite = "hilite";
  dothing($i,$hilite);
}

Although the assignment itself is probably more work then the '%2' (which is inherently just a bit-shift).

Wrikken