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, ...';
Community
  • 1
  • 1
Ahmed Fouad
  • 2,963
  • 10
  • 30
  • 54

4 Answers4

131

Use implode:

 $tags = implode(', ', array('tag1','tag2','tag3','tag4'));
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 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 01 '16 at 05: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 )

RutZap
  • 381
  • 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
  • 8,109
  • 6
  • 45
  • 82
7

Simply implode:

$tags = implode(", ", $tags);
Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87