Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to comma separated values

I'm using PHP.

I have the following array:

Array
(
[home] => 9
[pets] => 8
[dogs] => 7
[shampoo] => 7
[cover] => 6
)

I want to create a comma separated list which is:

home,pets,dogs,shampoo,cover

Here's what I'm trying but giving me blank string ($words is the array):

$myWords = implode(',',$words[0]);

Do I need to loop instead?

like image 998
StudioTime Avatar asked Jun 16 '26 22:06

StudioTime


2 Answers

You're close. You just need the keys from that array. array_keys() will do that for you:

 $myWords = implode(',',array_keys($words));
like image 162
John Conde Avatar answered Jun 19 '26 11:06

John Conde


$string = implode(',', array_keys($words));

$words[0] does not exist in your array, because all of your keys are strings.

like image 43
Marc B Avatar answered Jun 19 '26 11:06

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!