Home / Multiple variable assignment with PHP

Multiple variable assignment with 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: $cn";

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.