|
Posted by Tyno Gendo on 04/11/07 23:02
Anonymous wrote:
>> Yes, definately a syntax to avoid, seems unpredictable at best...
>
> No, I would always expect what you got, it's perfectly predictable. You
> should read up how the ++ operators work.
>
>> <?php
>> $i = 2;
>> echo $i++ + 1; /// i'd expect 4, gives 3, ignores ++ increment
>
> Does not ignore the increment, but $i++ returns the value before
> incrementation, then increments. So $i++ + 1 correctly returns 2 + 1,
> which is 3.
>
>> $i = 2;
>> echo $i++ + $i; // expect 5, gives 5, applies ++ increment
>
> Correct. First $i++ is executed which returns 2, then increments a to 3,
> then the + $i will be evaluated, so the expression will be 2 + 3, which
> is 5.
>
>> $i = 2;
>> echo $i++ + $i++ + 1; // expect 7, get 6
>> ?>
>
> Why do you expect 7? First $i++ returns 2, increments $i to 3, so the
> expression will be 2 + $i++ + 1, with $i = 3, the second $i++ will
> return 3 and increment $i to 4, so we have 2 + 3 + 1, which equals 6.
>
> Bye!
I have now, and it makes sense...
I'm glad this thread came up on alt.php as I'd never even considered
doing the $i = $i++ before someone posted it on there, but now I've seen
someone do it then I won't make the same mistake they did, and I didn't
realise that a '++' first returned the original value as if it was a
function...
But clearly, the PHP man says it does:
"$a++ Post-increment Returns $a, then increments $a by one."
Navigation:
[Reply to this message]
|