Use implode:
$tags = implode(', ', array('tag1','tag2','tag3','tag4'));
Answer from John Conde on Stack OverflowUse implode:
$tags = implode(', ', array('tag1','tag2','tag3','tag4'));
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 )
How to convert an array to a comma-delimited string in PHP - Stack Overflow
php - How to transform array to comma separated words string? - Stack Overflow
php - Array to comma separated string? - Stack Overflow
How do I create a comma-separated list from an array in PHP? - Stack Overflow
I would turn it into CSV form, like so:
$string_version = implode(',', $original_array)
You can turn it back by doing:
$destination_array = explode(',', $string_version)
I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:
$stringRepresentation= json_encode($arr);
You want to use implode for this.
ie:
$commaList = implode(', ', $fruit);
There is a way to append commas without having a trailing one. You'd want to do this if you have to do some other manipulation at the same time. For example, maybe you want to quote each fruit and then separate them all by commas:
$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
$fruitList .= $prefix . '"' . $fruit . '"';
$prefix = ', ';
}
Also, if you just do it the "normal" way of appending a comma after each item (like it sounds you were doing before), and you need to trim the last one off, just do $list = rtrim($list, ', '). I see a lot of people unnecessarily mucking around with substr in this situation.
This is how I've been doing it:
$arr = array(1,2,3,4,5,6,7,8,9);
$string = rtrim(implode(',', $arr), ',');
echo $string;
Output:
1,2,3,4,5,6,7,8,9
Live Demo: http://ideone.com/EWK1XR
EDIT: Per @joseantgv's comment, you should be able to remove rtrim() from the above example. I.e:
$string = implode(',', $arr);