Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert items in array to a comma separated string in PHP? [duplicate]

Tags:

arrays

php

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, ...'; 
like image 978
Ahmed Fouad Avatar asked Jun 07 '12 16:06

Ahmed Fouad


People also ask

How do you convert an array to a comma with strings?

To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

How do I separate comma separated values in PHP?

The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.

How do you use comma separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 Answers

Use implode:

 $tags = implode(', ', array('tag1','tag2','tag3','tag4')); 
like image 89
John Conde Avatar answered Oct 02 '22 16:10

John Conde


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 )

like image 43
RutZap Avatar answered Oct 02 '22 15:10

RutZap