Alex Rivera | Logout

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

Asked 2009-01-10T19:19:28.030
10

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?

Edit
Report

3 Answers

7

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)
answered 2009-01-10T19:31:40.627
6

It doesn't matter for a few, short, strings. Use whatever is clearer to read.

But if you have lots of them (say thousands) not so short ones, you'll probably want to keep them in an array and join them together. (As it happens such code is often as easy to read as concatenating the strings using ".=", so you're not sacrificing clarity on the altar of performance.)

EDIT: I don't think my above thinking is valid. PHP's strings are mutable, right?

answered 2009-01-10T19:32:00.923
0

There is no meaningful difference. It's just a matter of coding preference.

answered 2009-01-11T10:14:35.183

Your Answer