Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add commas in a string of values

Tags:

php

I have an array and I'm trying to concatenate some values of this array. Currently, $all looks like: "AmazonSonySmashwordsBN" (see code below)

How do I make it look like: "Amazon, Sony, Smashwords, BN"

I understand how to concatenate. My problem is, I don't want a comma if one of the $bookcategory strings is empty.

$book = array("18"=>'BN', "19"=>'Amazon', "20"=>'Sony', "21"=>'Kobo', "22"=>'Smashwords', "23"=>'Apple', "24"=>'Android');

$bookcategory1 = $book[$catagory1];
$bookcategory2 = $book[$catagory2];
$bookcategory3 = $book[$catagory3];
$bookcategory4 = $book[$catagory4];


$all = $bookcategory1 . $bookcategory2 . $bookcategory3 . $bookcategory4; 

echo $all;

Thanks!

like image 487
user2816376 Avatar asked Dec 02 '22 21:12

user2816376


1 Answers

You can join your array with the implode function:

echo implode(', ', array_values($book));

If you want to display some elements of your array only (it seems you only show 4 categories here), reduce your array to 4 elements (or create a new one with these values) and use implode.

like image 100
Maxime Lorant Avatar answered Dec 09 '22 15:12

Maxime Lorant