|  | Posted by Anonymous on 04/11/07 22:25 
Steve wrote:>
 > someone asked a question in alt.php about a problem they were having with an
 > algorytm. it contained something to the effect of:
 >
 > $i = $i++;
 >
 > some example code they'd snatched somewhere. in a loop, the expected $i to
 > increment. i explained why i thought it would not - as it does not. however,
 > i want to make sure i gave a valid answer.
 >
 > anyone have input?
 
 I don't read alt.php so I don't know what you wrote, but the answer is
 pretty obvious.
 
 First, the ++ operators are increment operators. They execute an
 incrementation of the variable by 1. $i++ by itself already executes $i
 = $i + 1, which the original poster most likely wanted to do. But the
 increment operators also return a value for further usage. The
 post-increment operator returns the value before the variable was
 incremented, the pre-increment operator returns the value after
 incrementation.
 
 $i++ is post-increment. That means, first the content of the variable is
 evaluated, then it is incremented, then the evaluated (meaning the
 former) value is passed to the equation which gets executed and resets
 $i to its former value.
 
 In other words, what the line $i=$i++; actually does is:
 
 $evaluated = $i; //first save the current value for later usage
 $i = $i + 1; // execute the increment after that because we are doing
 post-increment
 $i = $evaluated; // execute the actual equation
 
 So I'd be very surprised if $i would change. :-)
 
 Imagine the code:
 
 $a = 1;
 $b = $a++;
 
 Then $a would be 2 and $b would be 1. If you wanted $b to get the new
 value of $a and not the old one you would have to use pre-increment. The
 variable would first be incremented and the new value passed to the
 equation. Pre-increment would be ++$a instead of $a++. And if you wanted
 $b to be just 1 larger than $a without changing $a at all you would
 write $b = $a + 1;.
 
 Pretty simple once you understand the concept of the increment (or
 decrement) operators. If you (respectively the original posters) are
 still unsure about them you should read them up in chapter 14 und 15 of
 the PHP manual. They give several examples for using them. Feel free to
 forward my explanation to alt.php, Steve.
 
 Bye!
  Navigation: [Reply to this message] |