Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?

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?

like image 838
Darryl Hein Avatar asked Jan 10 '09 19:01

Darryl Hein


People also ask

What is an efficient way to combine two variables in PHP?

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.

Why we use concatenate in PHP?

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 .

How do I concatenate one string or more?

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.

How can you concatenate two or more strings in PHP?

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.


2 Answers

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";
like image 124
jmucchiello Avatar answered Oct 22 '22 02:10

jmucchiello


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)
like image 28
Ivan Avatar answered Oct 22 '22 01:10

Ivan