Is there a difference or is one better than the other of the following:
$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
Or
$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
Is there a speed difference or is there a reason why you'd pick one over the other?
The concatenate term in PHP refers to joining multiple strings into one string; it also joins variables as well as the arrays. In PHP, concatenation is done by using the concatenation operator (".") which is a dot.
Prepend and Append Strings in PHP You can use the concatenation operator . if you want to join strings and assign the result to a third variable or output it. This is useful for both appending and prepending strings depending on their position. You can use the concatenating assignment operator .
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' . = '), which appends the argument on the right side to the argument on the left side.
Both PEZ and Topbit are correct. I just want to point out something I think looks better than has been seen here:
$var = "line 1 \n";
$var .= "line 2 \n";
versus
$var = "line 1 \n"
. "line 2 \n";
I much prefer the second one to the first one as visually it is obvious your result is the one string $var. It also prevents stupid bugs like:
$var = "line 1 \n";
$var .= "line 2 \n";
$vat .= "line 3 \n";
$var .= "line 4 \n";
There is a small difference if you echo the string.
echo $var1,$var2,$var3 // comma (echo with multiple arguments)
is slightly faster than
echo $var1.$var2.$var3 // dot (concat and echo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With