12

Here is some example code:

$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

What does the period character do in the middle of each piece of the string?

For example,

"blabla" . "blabla" . "blablalba";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mhz
  • 1,019
  • 2
  • 8
  • 30

3 Answers3

13

This operator is used to combine strings.

EDIT

Well, to be more specific if a value is not a string, it has to be converted to one. See Converting to a string for a bit more detail.

Unfortunately it's sometimes mis-used to the point that things become harder to read. Here are okay uses:

echo "This is the result of the function: " . myfunction();

Here we're combining the output of a function. This is okay because we don't have a way to do this using the standard inline string syntax. A few ways to improperly use this:

echo "The result is: " . $result;

Here, you have a variable called $result which we can inline in the string instead:

echo "The result is: $result";

Another hard to catch mis-use is this:

echo "The results are: " . $myarray['myvalue'] . " and " . $class->property;

This is a bit tricky if you don't know about the {} escape sequence for inlining variables:

echo "The results are: {$myarray['myvalue']} and {$class->property}";

About the example cited:

$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

This is a bit tricker, because if we don't use the concatenation operator, we might send out a newline by accident, so this forces lines to end in "\r\n" instead. I would consider this a more unusual case due to restrictions of email headers.

Remember, these concatenation operators break out of the string, making things a bit harder to read, so only use them when necessary.

onteria_
  • 68,181
  • 7
  • 71
  • 64
  • 1
    `$myarray['myvalue']` and `$class->property` can actually be inlined without `{}`: `"The results are: $myarray[myvalue] and $class->property"`, but this can be a matter of taste/ambiguity/possibility for errors. If you're doing this a lot though (I mean, ***a lot***), concatenation may be better because it's faster. – deceze May 24 '11 at 01:19
  • Thanks for the throughout explanation! – mhz May 26 '11 at 04:05
6

It's the concatenation operator. It joins two strings together. For example:

$str = "aaa" . "bbb"; // evaluates to "aaabbb"
$str = $str . $str;   // now it's "aaabbbaaabbb"
Ry-
  • 218,210
  • 55
  • 464
  • 476
4

It's the concatenation operator, concatenating both strings together (making one string out of two separate strings).

deceze
  • 510,633
  • 85
  • 743
  • 889