Page 1 of 1

Small script question..

Posted: Fri Apr 06, 2012 8:57 pm
by Austin
I have a very small script that I need help with. I'm learning PHP, and I can't figure out why this loop won't work. Please help! =]

Here it is:

<?PHP
$counter = 0;
$start = 1;

for($start; $start < 11; $start++) {
$counter = $counter++;
print $counter . "<BR>";
}

?>

I posted this on another forum and COULD not understand their explanations. If you could, please answer this as if you were answering a 3 year old. =P

I am very new to programming. :) Thanks

Re: Small script question..

Posted: Fri Apr 06, 2012 9:42 pm
by MikeD
<?PHP
$counter = 0;
$start = 1;

for($start; $start < 11; $start++) {
$counter = $counter++;
print $counter . "<BR>";
}

?>
I have never found $counter = $counter++ to work.

Try $counter = $count + 1;

Re: Small script question..

Posted: Fri Apr 06, 2012 10:38 pm
by Callan S.
or $counter+=1;

Re: Small script question..

Posted: Fri Apr 06, 2012 10:53 pm
by Jackolantern
Or just $counter++. No assignment is needed. The increment operator (++) does not work like most other things in PHP. It actually alters the value of the variable it operates on, instead of returning the result of the operation and leaving the operand untouched. That is why this works:

Code: Select all

for ($x = 0; $x < 11; $x++) {
    //code
} 

Re: Small script question..

Posted: Sat Apr 07, 2012 3:09 am
by Austin
This:
"The increment operator (++) does not work like most other things in PHP. It actually alters the value of the variable it operates on, instead of returning the result of the operation and leaving the operand untouched."
is very helpful. Thanks.

I actually knew how to get it to work. I just wanted to understand why the script above doesn't.

I still don't really understand why $counter++ would work alone, and $counter = $counter++ won't..

I REALLY appreciate the responses, though. Thanks, guys. Any more help would be awesome and appreciated.

Re: Small script question..

Posted: Tue Apr 10, 2012 4:48 pm
by Jackolantern
$counter = $counter++ does not work because $variable++ is not just called the "increment operator", but the "post increment operator". It will only increment the variable once the line of code has run. It is probably just a timing issue with PHP due to the fact that the increment operator is not typically used that way. If you did want to use an increment operator like that, you would need to use the "pre increment operator", like this:

Code: Select all

$counter = ++$counter; 
However, this still suffers from the fact that this is not the intended usage of the operator, and because of that it may have strange effects in PHP. The recommended way to use it is still as a straight unary operation:

Code: Select all

$counter++;