...

View Full Version : odd even number

kenny873
04-07-2003, 05:21 AM
if I have a for loop :
for (\$i=0; \$i<count(\$replyDetails); \$i++){
...
bgcolor = 123 (OR 456)...
...
}
and will show bgcolor = 123 if \$i is an even number or \$i=0
and will show bgcolor = 456 if \$i is an odd number

how can i implement that?

Spookster
04-07-2003, 05:29 AM
for (\$i=0; \$i<count(\$replyDetails); \$i++){

if(\$i % 2 == 0)
echo \$i . " is even";
else
echo \$i . "is odd";
}

04-07-2003, 01:12 PM
Just to explain what Spookster did, we have a "%" which is a modulos. This means it takes the remainder of the division of two numbers (eg. Remainder of 10%2 is 0 from 10/2 = 5.0 -> which means no remainder).

So

if ((\$i % 2) == 0)

means for all numbers divisible by 2 (ie. every second number).

Mhtml
04-07-2003, 01:40 PM
Q. Is it better to do it using mod or like this?

if (\$xyz == 1){
\$bgColor = "red";
\$xyz = 0;
}else{
\$bgColor = "green";
\$xyz = 1;
}

Or is the diff non-existant?

04-07-2003, 01:51 PM
for (\$i=0; \$i<count(\$replyDetails); \$i++){

if(\$i % 2 == 0)
echo \$i . " is even";
else
echo \$i . "is odd";
}

For loop O(n)
if O(1)
echo O(1)
else O(1)
echo O(1)

Maximum time is O(n)

for (\$i = 0; \$i<count(\$replyDetails); \$i++)
{
if (\$xyz == 1){
\$bgColor = "red";
\$xyz = 0;
}
else
{
\$bgColor = "green";
\$xyz = 1;
}
}

for loop O(n)
if O(1)
\$bgcolor = "red" O(1)
\$xyz = 0 O(1)
else O(1)
\$bgcolor = "red" O(1)
\$xyz = 0 O(1)

total O(n)

In terms of big Oh time, they are equivalent, however, you have more variables in the second one that are changed, so if you are looking at it minutely, that is less efficient, but hardly noticable.

At least that's my understanding of it.

Mhtml
04-07-2003, 01:53 PM
Ok, thanks. :) I'm sure any gain in speed and preformance is good no matter how minute.

thox
04-07-2003, 02:16 PM
Source: Golden rules for optimising your pages (http://www.phpbuilder.com/columns/weerning20021209.php3?page=3)

Prefer '.....' to "....." because the server side PHP engine parses everything it finds between the " " while it doesn't control what is written between the two single quotes

By the way: <?php echo 'This is my var:',\$var,'!!'; ?> should be some milliseconds faster than <?php echo 'This is my var:'.\$var.'!!'; ?> (concatenated by a dot instead of the comma) and faster than <?php print 'This is my var:'.\$var.'!!'; ?>

every little helps <g>

Mhtml
04-07-2003, 02:25 PM
Okey dokey. :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum