Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## odd even number

if I have a for loop :
...
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?

• PHP Code:
``` for (\$i=0; \$i<count(\$replyDetails); \$i++){ if(\$i % 2 == 0)     echo \$i . " is even"; else     echo \$i . "is odd"; }  ```

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

• Q. Is it better to do it using mod or like this?
PHP Code:
``` if (\$xyz == 1){  \$bgColor = "red";  \$xyz = 0; }else{  \$bgColor = "green";  \$xyz = 1; }  ```
Or is the diff non-existant?

• PHP Code:
``` 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)

PHP Code:
``` 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.

• Ok, thanks. I'm sure any gain in speed and preformance is good no matter how minute.

• Source: Golden rules for optimising your pages

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>

• Okey dokey.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•