Concatenation string against imode array in PHP

I used Java for a long time as a standard method for creating long strings in parts, to add elements to an array and then explode the array.

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

But then with lots of data.

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

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

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

So my question is: are there any other reasons for choosing one approach over another, besides reading styles and code?

+6
string arrays php
source share
5 answers

For me, using an array implies that you are going to do something that cannot be done with simple string concatenation. Like sorting, uniqueness checking, etc. If you don't do anything like this, then string concatenation will be easier to read in a year or two for those who don't know the code. They will not have to wonder if the array will be controlled before it is blown up.

However, I use an immobilized array approach when I need to create a string with commas or "and" between words.

+8
source share

Choose a more readable one. Always. In this case, I will pick up the second application. Then optimize it if it is a bottleneck.

+3
source share

One (subtle) difference is clearly visible when creating a line separated by characters:

 <?php $out[] = 'a'; $out[] = 'b'; echo implode(',', $out); foreach($out as $o) { echo $o . ','; } ?> 

The first will print a,b , where the last will print a,b, Therefore, if you do not use an empty string as a separator, as was the case in your example, they usually prefer to use implode() .

+3
source share

Holy War of Concatenation-vs-implode: No, no difference.

+2
source share

it depends on what you want to do with the string / array and how you create it.

if you start with an array and have to sort it / manipulate certain elements, then I suggest implode

except that I usually use concatenation

0
source share

All Articles