73

Possible Duplicate:
How to create comma separated list from array in PHP?

Given this array:

$tags = array('tag1','tag2','tag3','tag4','...');

How do I generate this string (using PHP):

$tags = 'tag1, tag2, tag3, tag4, ...';
2
  • did you google first before posting the question here??? :):) Jun 7, 2012 at 16:42
  • 25
    I'd like to point out that Googling this problem brings you here to this page, so in effect this question is a self-fulfilling prophecy, as otherwise this page would not exist :) May 11, 2015 at 23:43

4 Answers 4

131

Use implode:

 $tags = implode(', ', array('tag1','tag2','tag3','tag4'));
1
  • 4
    This is a bad idea if you're trying to create reliable CSV strings. CSV has rules regarding commas inside fields, etc..
    – photocode
    Sep 1, 2016 at 5:03
24

Yes you can do this by using implode

$string = implode(', ', $tags);

And just so you know, there is an alias of implode, called join

$string = join(', ', $tags);

I tend to use join more than implode as it has a better name (a more self-explanatory name :D )

2
  • 2
    And the good thing is that both takes the almost same time to execute :) I made a benchmark Feb 26, 2014 at 13:16
  • 2
    Coming back at this after 5 years, I now tend to use implode instead of join, not sure why, but I find that explode-implode is more common in most codebases I've worked on now, and I prefer to align myself with the rest of the codebase in order to maintain a certain level of consistency.
    – RutZap
    Nov 30, 2017 at 11:10
13

Use PHP function Implode on your array

$mystring = implode(', ',$tags)
7

Simply implode:

$tags = implode(", ", $tags);

Not the answer you're looking for? Browse other questions tagged or ask your own question.