php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #20673 Inexplicable arithmetical error due to references
Submitted: 2002-11-27 07:04 UTC Modified: 2002-12-09 06:55 UTC
Votes:7
Avg. Score:3.6 ± 0.9
Reproduced:6 of 6 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: dakota at dir dot bg Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 4.3.0-dev/4.4.0-dev OS: Win 2000 NT/Linux
Private report: No CVE-ID: None
 [2002-11-27 07:04 UTC] dakota at dir dot bg
<? 
$a = 7;
$a = $a + $a++;
echo $a; 
//the result is 14;
?>

When I add a reference to $a, the behavior of $a + $a++ becomes inexplicable different. Note that $a isn't changed anywhere!

<?
$a = 7;
$b =& $a;
$a = $a + $a++;
echo $a; 
//the result is 15;
?>

The only difference is $b =& $a, but why $a takes care of references to itself?

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-11-29 13:11 UTC] sesser@php.net
never write something like $a = $a + $a++;

if you f.e. try such a construct in C you will get different
results depending on the compiler and/or optimisation level.
 [2002-11-30 09:28 UTC] dakota at dir dot bg
O.K. but it's PHP - not C. And, if it's wrong, why the parser don't warn me?
 [2002-12-09 06:55 UTC] andi@php.net
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;
?>


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC