Multiple Variable Assignment In Php

How many years have I been programming PHP for now? Over seven years so why has it taken me so long to discover something so simple. I discovered this not by chance however.

Several months ago I was doing some simple variable assignments like these below.

$var1 = 0;
$var2 = 0;
$var3 = 0;
$var4 = 0;

I sat there and looked at the above code and thought “This code isn’t DRY (Don’t Repeat Yourself) at all”. Then off the top of my head I typed this:

$var1 = $var2 = $var3 = $var4 = 0;

I looked at the code I had written, it made sense, it almost felt right but was PHP going to allow such a thing? I saved and took plunge with a browser refresh. No syntax errors. It actually worked!

After years of looking at PHP code both my own and that written by others, for some reason I had not seen this simple tip so I’m writing about it in the hope that I might pass something useful onto someone else. Of course, multiple variable assignment isn’t only limited to PHP, Ruby can do it to (at least for integers). So give it a go in your language.