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.

Ruby on Rails: image_submit_tag and :confirm

I was told about an issue today with the image_submit_tag not supporting the :confirm method on the element:

<%= image_submit_tag('buttons/submit.gif', { :confirm => 'Are you sure?' }) %>

so I thought I’d share a quick fix which would be the actual javascript returned by the function:

<%= image_submit_tag('buttons/submit.gif', { :onclick => 'return
confirm(\'Are you sure?\');' }) %>

Hope this can save some people time…