Reply to Re: $i = $i++

Your name:

Reply:


Posted by Jerry Stuckle on 04/12/07 04:13

Gordon Burditt wrote:
>> Yes, definately a syntax to avoid, seems unpredictable at best...
>>
>> <?php
>> $i = 2;
>> echo $i++ + 1; /// i'd expect 4, gives 3, ignores ++ increment
>
> Please get your expecter fixed. $i++ returns the value *BEFORE*
> the increment. (If you want ++$i, you know where to find it.) This
> one is unambiguous since all possible orders come up with the same
> result.
>
> For the other expressions involving $i++ and another reference to $i's
> value to give a resource returning Donald Trump, who's going to find the
> programmer and say "You're Fired".
>

Actually, not entirely true.

<?
$i = 2;
echo $i++ + $i++ + 1; // expect 7, get 6
?>

can return either 5 or 6.

The reason here is - the order of operations is guaranteed, but not the
order the *operands* are evaluated.

For instance - the first $i++ is incremented to 3 and the old value (2)
returned. But there is no guarantee the value of the second $i++ will
be evaluated before or after the first $i++ has been processed.

This might be:

2 + 3 + 1

but

2 + 2 + 1

could also be valid, as could

3 + 2 + 1

Or course the first and third return the same value - but only because
it's addition.

In either case, however, $i will be incremented to 4 at the end.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация