tags:

views:

376

answers:

5

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.

$out[] = 'a';
$out[] = 'b';
echo implode('', $out);

But then with a lot of data.

The (standard PHP) alternative is to use string concatenation.

$out = 'a';
$out .= 'b';
echo $out;

To my surprise there seems to be no speed difference between both methods. When there is significant time difference usually it is the concatenation that seems faster, but not all of the time.

So my question is: are there - apart from style and code readability - any other reasons to choose one approach over the other?

+1  A: 

Choose the more readable one. Always. This case, i would pick up the second apporach. Then optimize it, if it's a bottleneck.

erenon
No it is not a bottleneck, just curious. Anyhow I already mentioned readability.
Matijs
I can only agree to this - never do something since a micro-benchmark shows it's 0.0001% faster. with XDebug or zendDebugger there are profilers for PHP and if that's not enough there are ways to profile the PHP runtime too, time spent there is way better used than in maintianing "optmized" code (and often it's even cheaper to run some more hardware than paying the developer)
johannes
+1 just choose the most appropriate one. If `implode` solves the problem elegantly, use it.
Ben James
He said "apart from ... readability".
Lucas Oman
+3  A: 

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.

Scott Saunders
+1  A: 

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().

Duroth
One could do:$first = true;foreach ($out as $o) { if ($first) $first = false; else echo ','; echo $o;}That should give you a,b instead.
Adam Raney
@Raney: why all the trouble when `implode()` way is easier?
Lukman
A: 

The concatenation-vs-implode holy war aside: No, there is no difference.

Lucas Oman
A: 

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

Raz