How to add commas to a value string

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

How do I look like this: Amazon, Sony, Smashwords, BN

I understand how to concatenate. My problem is that I don't want a comma if one of the lines of $ bookcategory 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!

+4
source share
7 answers

You can join your array using the function implode:

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

(, 4 ), 4 ( ) implode.

+8

:

$all = "$bookcategory1, $bookcategory2, $bookcategory3, $bookcategory4"; 

, .

$all = $bookcategory1 .", ". $bookcategory2 .", ". $bookcategory3 .", ". $bookcategory4; 
+3

$a. ",". $b - ... script:

    $a = "this";
    $b = "that";
    $c = "other thing";
    echo "${a},${b},${c}\n";

:

, ,

+2

:

$str = implode(', ', array_values($book));
//=> BN, Amazon, Sony, Kobo, Smashwords, Apple, Android
+1
$all = $bookcategory1 . $bookcategory2 . $bookcategory3 . $bookcategory4; 

:

$all = $bookcategory1 . ", " . $bookcategory2 . ", " . $bookcategory3 . ", " . $bookcategory4; 
+1

, , .

$all = $bookcategory1 . ", " . $bookcategory2 . ", " . $bookcategory3 . ", "  $bookcategory4; 
+1

, , , :

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

Normal concatenation with $book[0] . ", " . $book[1] ...or implode(", ",$book), the output will begin with an extra comma ( , Amazon, Sony), since it adds an empty value. To skip the space, you need to filter the value:

$all = implode(", ",array_filter($book));

echo $all;
  // Amazon, Sony, Kobo, Smashwords, Apple, Android

http://codepad.org/CNvhYYBm

+1
source

All Articles