Multiple variable assignment with PHP
Posted December 14th, 2009 in PHP
This post shows how it is possible to assign multiple variables with the same value with PHP. This can be useful if initializing multiple variables with the same initial value or if needing to make multiple copies of a value and then manipulate each separately.
Assigning multiple variables
Multiple variables can be assigned by using = multiple times on the same line of code like so:
$c = $b = $a;
The above is a more compact equivilent of this:
$b = $a; $c = $b;
Here's an example:
$a = 'A'; $b = 'B'; $c = 'C'; $c = $b = $a; echo "a: $a, b: $b, c: $c";
This will output this:
a: A, b: A, c: A
As you can see all three variables now contain "A" which is what $a was set to initially.
Concatenating multiple variables
This second example isn't very ideal as it can be confusing so I wouldn't recommend it but include it here for completeness.
Just as multiple assignments can be done with multiple =, multiple concatenations can be done with .= like so:
$c .= $b .= $a;
The above is a more compact, but possibly confusing, equivilent of this:
$b .= $a; $c .= $b;
And here's an example of this:
$a = 'A'; $b = 'B'; $c = 'C'; $c .= $b .= $a; echo "a: $a, b: $b, c: $c\n";
The above will output this:
a: A, b: BA, c: CBA
I'm not sure if or when you would use the multiple concatenation like this and as I already mentioned above only include it for completeness.
Related posts:
- How to use static variables in a PHP function (Monday, January 9th 2012)
- Multiple variable assignment with Javascript (Tuesday, January 12th 2010)
- PHP's nowdoc strings (Friday, December 4th 2009)
- Copying an object in PHP with clone (Tuesday, November 10th 2009)
- PHP's heredoc strings (Monday, September 21st 2009)
- Type casting with PHP (Sunday, August 10th 2008)

Comments
blog comments powered by Disqus