开发者

change a variable based on even/odd status of another variable?

开发者 https://www.devze.com 2023-01-08 20:18 出处:网络
for($i=0;$i<$num;$i++) { if($i==even) $hilite=\"hilite\"; dothing($i,$hilite); } This is basically what I want to accomplish.
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? 开发者_如何学CIs there a simpler way?


if ($i % 2 == 0)


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).


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


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


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!
}
0

精彩评论

暂无评论...
验证码 换一张
取 消