。=在这段代码中是怎么工作的?

I was given this question as part of learning PHP.

What is the final value of $a?

$a .= "a";
$a .= "b";
$a .= "c";

I know it outputs "abc" and I understand that ".=" is a concatenation assignment, but I'm still a little unclear what is actually going on here. When I remove the periods I get "c", which makes sense that it would take the last item.

Thanks for any clarity.

$a .= "a" 

...is shorthand for ...

$a = $a . "a"

At the beginning, $a is empty.

$a .= "a"
// now $a == "a"
$a .= "b"
// now $a == "a" . "b" == "ab"
$a .= "c"
// now $a == "ab" . "c" == "abc"

Yes, exactly, it's concat'ing it. The following two lines are equivalent.

$a = $a . "a"   
$a .= "a"

When you use .= in PHP you are practically gluing strings together into one.

Test your code by pasting it in here: http://writecodeonline.com/php/

then write another line to output the content of the variable a

$a .= "a";
$a .= "b";
$a .= "c";
echo $a;

The final result of the variable a is "abc" because "a" + "b" + "c" = "abc" - Concatenation!

So in summary, think of the following: The variable a is simply a container... When we use the assignment operator (=), we remove whatever its in the container and replace it with the new value we are assigning, this is why when you used = the final result was the character c. Because it kept on replacing the original content.

When we use concatenation, .=we continue to APPEND, instead of replacing it.

$a .= "a";   // $a =$a . 'a' ie a= 'a'
$a .= "b"; //  $a =$a . 'b' ie a= 'ab'
$a .= "c"; // $a =$a . 'c' ie a= 'abc'

You can not use $a .= "a" when $a is not defined. in this case you should get "Undefined variable" warning with a correct PHP configuration. Try to fix this problem to get ride of any unexpected value;