String Variable Concatenation
I stumbled across something odd today in PHP:
$r = ''; $r .= $r .= $r .= 'a';
Now, personally, I’d have expected a syntax error from the above code, but the result was even more confusing at first…
print $r; // 'aaaa'
Not sure if this was the expected output or not I tested similar code in other languages:
Ruby:
r = '' r += r += r += 'a' puts r # 'a'
Python:
r = '' r += r += r += 'a' # File "", line 1 # r += r += r += 'a' # ^ # SyntaxError: invalid syntax
Javascript:
var r = ''; r += r += r += 'a'; alert(r); // 'a'
Perl:
my $r = ''; $r .= $r .= $r .= 'a'; print $r; // 'aaaa'
That explains it!
So the reason the string is ‘aaaa’ seems to be that the code is evaluated from right to left:
$r = ''; $r += $r += $r += 'a'; // How it works: // // $r += 'a'; // 'a' // $r += $r += 'a'; // 'a' + 'a'; // $r += $r += $r += 'a'; // 'aa' + ('a' + 'a')
I don’t think it’s a bug, well, at least I assume not, but is there a name for this?
Update: I asked some clever people for help understanding it.