php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #63978 Strange behaviour with precedence order
Submitted: 2013-01-12 17:46 UTC Modified: 2013-01-15 13:46 UTC
From: bobwei9 at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: master-Git-2013-01-12 (Git) OS: Irrelevant (OS X 10.8)
Private report: No CVE-ID: None
 [2013-01-12 17:46 UTC] bobwei9 at hotmail dot com
Description:
------------
I think the test script should be self explaining.

Order is somewhat strange.

Once it seems to be evaluated as

$first = (+$i); // => 0
$second = ($i += 3); // => 3
$result = $first + $second; // => 3

and once as:

$second = ($i += 3); // => 3
$first = ($i); // => 3
$result = $first + $second; // => 6

Test script:
---------------
php > $i = 0; print (+ $i + ($i += 3))."\n";
3
php > $i = 0; print ($i + ($i += 3))."\n";
6

Expected result:
----------------
I'd expect that the parenthesis are only resolved if encountered and not first resolved, then the variable replaced by its value.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-01-15 13:08 UTC] cataphract@php.net
-Status: Open +Status: Not a bug
 [2013-01-15 13:08 UTC] cataphract@php.net
+ is documented as having left-to-right associativity. So:

+ $i + ($i += 3)

is the same as

(0 + $i) + ($i += 3)

Which of the two operands to the "outside" addition is evaluate first is not specified anywhere in the manual. The implementation evaluates the first argument first in this case. In your other example, the first operand is just a variable, so PHP uses that variable directly in the final addition, at which point it's value is already 3.

To sum up, you cannot expect the operands to be evaluated in any specific order.
 [2013-01-15 13:46 UTC] bobwei9 at hotmail dot com
But even when I use parenthesis like (($i) + ($i += 3)), it is handeled as if there 
are none around $i!
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 23:01:33 2025 UTC