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?

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?
PHP Code:
for ($i=0; $i<count($replyDetails); $i++){
if($i % 2 == 0)
echo $i . " is even";
else
echo $i . "is odd";
}
Spookster
CodingForums Supreme Overlord
All Hail Spookster
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).
Duniyadnd
Q. Is it better to do it using mod or like this?
Or is the diff nonexistant?PHP Code:
if ($xyz == 1){
$bgColor = "red";
$xyz = 0;
}else{
$bgColor = "green";
$xyz = 1;
}
Omnis mico antequam dominus Spookster!
For loop O(n)PHP Code:
for ($i=0; $i<count($replyDetails); $i++){
if($i % 2 == 0)
echo $i . " is even";
else
echo $i . "is odd";
}
if O(1)
echo O(1)
else O(1)
echo O(1)
Maximum time is O(n)
for loop O(n)PHP Code:
for ($i = 0; $i<count($replyDetails); $i++)
{
if ($xyz == 1){
$bgColor = "red";
$xyz = 0;
}
else
{
$bgColor = "green";
$xyz = 1;
}
}
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.
Duniyadnd
Ok, thanks. I'm sure any gain in speed and preformance is good no matter how minute.
Omnis mico antequam dominus Spookster!
every little helps <g>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.'!!'; ?>
Okey dokey.
Omnis mico antequam dominus Spookster!