Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation vs array implode in PHP

Tags:

arrays

string

php

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?

like image 496
Matijs Avatar asked Dec 04 '09 14:12

Matijs


1 Answers

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.

like image 69
Scott Saunders Avatar answered Sep 26 '22 00:09

Scott Saunders