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?
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.
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