Having used Java for a long time my standard method for creating long strings piece by piece was to add the elements to an array and then implode the array.
The concatenation-vs-implode holy war aside: No, there is no difference.
One (subtle) difference is clearly visible when generating a character-seperated string:
<?php
$out[] = 'a';
$out[] = 'b';
echo implode(',', $out);
foreach($out as $o) {
echo $o . ',';
}
?>
The first one will print a,b
where the latter will print a,b,
. So unless you're using an empty string as a seperator, as you did in your example, it's usually preferred to use implode()
.
it depends on what you want to do with the string / array and how you create it
if you start with an array and need to sort it / manipulate certain elements, then i suggest implode
other than that i usually use concatenation
To me, using an array implies that you're going to do something that can't be done with simple string concatenation. Like sorting, checking for uniqueness, etc. If you're not doing anything like that, then string concatenation will be easier to read in a year or two by someone who doesn't know the code. They won't have to wonder whether the array is going to be manipulated before imploded.
That said, I take the imploded array approach when I need to build up a string with commas or " and " between words.
Choose the more readable one. Always. This case, i would pick up the second apporach. Then optimize it, if it's a bottleneck.