Click to See Complete Forum and Search --> : counter++


72newbie
08-24-2008, 08:47 PM
I have a script that counts items. On one server and test site it works, on another server it works but instead of counting 4 items then giving a break for a new row it's counting three items on the first row, 4 items for all the center rows then one item on the last row.

it looks like this:

$background = ($counter++%4) ? '' : '</tr><tr>';

I am completely baffled why it would count different on two different servers, the script is close to the same but not exactly and it uses an includes folder with functions and classes and is pretty complex. On top of that not all the files are the same from the test site to the live site.

I've searched through the files and can't find : function counter

Can you explain how this might work and what else it requires to work?

NogDog
08-24-2008, 08:59 PM
This...
$background = ($counter++%4) ? '' : '</tr><tr>';...is functionally equivalent to this...

$counter = 1; // I'm just guessing it starts at 1
if($counter % 4 != 0) // it's not evenly divisible by 4
{
$background = '';
}
else
{
$background = '</tr><tr>';
}
$counter = $counter + 1;

Does that help you see what's happening?

72newbie
08-24-2008, 09:11 PM
Yes, thank you very very much! NogDog you a very very helpful!
I have another question though, why does the last line do end like this:
$counter = $counter + 1;

NogDog
08-24-2008, 09:23 PM
At some point the counter needs to be incremented before the next iteration of the loop. $counter++ increments the value by one after its starting value is used in the current expression. Conversely, ++$counter increments its value before it is evaluated in the expression (so the expression would then use the new, increased value.

So in my above example, I could have used any of the following to the same effect, but I was just trying to use the most obvious one.

$counter += 1;
$counter++;
++$counter;

72newbie
08-24-2008, 09:31 PM
Ok, this is making my head spin just a bit. I moved the files from the live server to the test server, no problem. BUT if i use the code like below I can recreate the problem
it looks like:
XXX
XXXX
XXXX
X
instead of
XXXX
XXXX
XXXX

could the server itself be causing this?

:
if(++$counter%4)
{
$background = '';
}
else
{
$background = '</tr><tr>';
}

NogDog
08-24-2008, 09:42 PM
My guess is that something is different (duh!) that is causing the initial value of $counter to be different. You may want to explicitly set it (probably to 1) right before you start the loop where this code is.

72newbie
08-24-2008, 09:52 PM
That was easy enough,NogDog, we are awesome! :)