When one plus one does not equal two

Can someone explain this PHP code?

$a = 1;
$x = &$a;
$b = $a + ++$a;
print $b;

Prints 4. I expected 3 (which you get if you remove $x = &$a;). I just don't get it.

Comments

I would have expected 4. The

I would have expected 4. The only thing that surprised me is that you said if you remove the $x = &$a you get 3. When I tested it I got 4 in both cases, however, which is good, because it wouldn't have made sense the other way.

What happens is the ++$a has higher precedence than anything else and gets executed first. So before the $a + ++$a, $a is 1, but after the ++$a, $a is 2. Then the expression is like 2+2 = 4.

What didn't you get and how'd you get it to print 3 before? And what PHP version were you using?

Keith
http://www.keithdevens.com/

http://bugs.php.net/bug.php?id=20673

[...]Like in most other programming languages you can't use post/pre increment operators on a variable which is used more than once in an expression. The result is undefined. We won't print out a warning (like most other languages).
If you want the result to be 16 then do the following:
$a = 7;
$b =& $a;
$a++;
$a = $a + $a;
echo $a;
//the result is 15;

Take a look for yourself

<?php
$a = 1;
$b = $a + ++$a;
print $b;
?>
C:\bin\php>php-cli test.php
3
C:\bin\php>cat test.php
<?php
$a = 1;
$x = &$a;
$b = $a + ++$a;
print $b;
?>
C:\bin\php>php-cli test.php
4
C:\bin\php>php-cli -v
4.2.3

Thanks

Thanks You
_________________________

Sohbet & Muhabbet