________________________________ From: tedd <tedd.sperling@xxxxxxxxx> To: php-general@xxxxxxxxxxxxx; ash@xxxxxxxxxxxxxxxxxxxx; Daevid Vincent <daevid@xxxxxxxxxx> Sent: Wed, October 7, 2009 12:42:41 PM Subject: RE: Whacky increment/assignment logic with $foo++ vs ++$foo At 1:59 PM +0100 10/7/09, Ashley Sheridan wrote: >>On Wed, 2009-10-07 at 08:54 -0400, tedd wrote: >>At 6:15 PM -0700 10/6/09, Daevid Vincent wrote: >>>Except that: >>> >>>$a = 123; >>>$b = $a++; >>>echo $b; //gives 123, not 124 >>> >>>as you logically expect it to and common sense would dictate, regardless of >>>what K&R or anyone else says. >> >>That's not the way I look at it. >> >> $b = $a++; >> >>means to me "take the value of $a and assign to $b and then increment $a." >> >>Whereas: >> >> $b = ++$a; >> >>means to me "increment $a and take the value of $a and assign to $b." >> >>Cheers, >> >>tedd >> >> > >Which is exactly the reason for the two operators in C. > >Thanks, >Ash Ash: The reason was simply to provide a different way of doing something. For example, take the statements of: $a = 10; $b = a$++; // $b = 10 and $a = 11 This post-increment operator was a way to assign 10 to $b and increment $a in one statement. Whereas: $a = 10; $b = ++a$; // $b = 11 and $a = 11 This pre-increment operator was a way to increment $a and also assign that value to $b. Both are perfectly valid ways of using the operator. Also realize that the pre-decrement and post-decrement operators worked in similar fashion. Now why would someone want to do that? There could be many reasons, but that was left to the programmer to use as he/she needed. However, what I find wacky about all of this is: for($i=1; $i<=10; $i++) { echo($i); } and for($i=1; $i<=10; ++$i) { echo($i); } Do exactly the same thing. I would have expected the first to print 1-10, while the second to print 2-10, but they both print 1-10. Cheers, tedd Tommy>> Why would expect to print 2-10? The way I read the for loop is: start $i with 1, do loop body until $i <= 10, increment $i before next loop. So whether post/pre-increment doesn't matter logically. Moreover, your loop can also be written as: for ($i=1; $i <= 10;) { echo ($i++); } PS: I hate to send reply in 'rich text' but Yahoo's plain text screw up the quote... I think it's time to switch over to gmail... -- ------- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php