67

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, ...';
Community
  • 1
  • 1
Ahmed Fouad
  • 2,823
  • 10
  • 29
  • 54
  • did you google first before posting the question here??? :):) – Nishu Tayal Jun 07 '12 at 16:42
  • 22
    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 :) – System24 Tech May 11 '15 at 23:43

4 Answers4

125

Use implode:

 $tags = implode(', ', array('tag1','tag2','tag3','tag4'));
John Conde
  • 212,985
  • 98
  • 444
  • 485
  • 3
    This is a bad idea if you're trying to create reliable CSV strings. CSV has rules regarding commas inside fields, etc.. – photocode Sep 01 '16 at 05:03
22

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 )

RutZap
  • 261
  • 1
  • 6
  • 2
    And the good thing is that both takes the almost same time to execute :) I made a benchmark – Airy Feb 26 '14 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 '17 at 11:10
13

Use PHP function Implode on your array

$mystring = implode(', ',$tags)
GDP
  • 7,863
  • 6
  • 42
  • 79
7

Simply implode:

$tags = implode(", ", $tags);
Mike Mackintosh
  • 13,530
  • 6
  • 58
  • 85