In PHP, why do you use ".="?

  • Thread starter Thread starter luckyouaskhole
  • Start date Start date
L

luckyouaskhole

Guest
What is the .= used for, in this example: (i got this from the book i'm reading and the book doesn't explain why)

$msg = "E-MAIL SENT FROM WWW SITE\n";

$msg .= "Sender's Name:\t$_POST[sender_name]\n";

$msg .= "Sender's Name:\t$_POST[sender_email]\n";

$msg .= "Sender's Name:\t$_POST[message]\n";

I've noticed that you use the .= for the same variable after the first time it has been defined. Doesn't redefining a variable overwrite the previous value? Or is that what .= does or what?
 
$var .= "string"

is the same as

$var = $var . "string"

. is the concatination operator, and = is the assignment operator, so .= combines them by concatinating the strings and assigning them to the first one.

So in this code:

$string1 = "Hello "

$string1.="world!"

string1 takes on the value of "Hello world!"
 
Example 1:
$msg = "hi";

$msg is like a box.
In Example 1, we empty the $msg box and place "hi" inside the box.

$Example 2
L1: $msg = "hi";
L2: $msg .= "-there";

In Example 2
L1, we empty the $msg box and place "hi" inside the box.
L2, you notice it's not =, it's .= (<DOT><EQUALS>) which adds the new text to the box, but keeps the old text.
This is the same as $msg = $msg . "-there";
In the end $msg is "hi-there"

$num += 10;
$num = $num + 10;

$num -= 10;
$num = $num - 10;

$num *= 10;
$num = $num * 10;

I hope you understand.
Good luck and hope this helped
 
Back
Top