av17
av17

Reputation: 105

Print the values of a flat array as a comma-separated string

I'm trying to print each value in this array as a comma-delimited string.

$domainext = array("com","net","edu","uk","au","in","biz","ca","cc","cd","bz","by");

Here is how I'm doing it.

 foreach ($domainext as $ext){
     $ext = implode(', ', $domainext);
     echo $ext."<br>";
     echo "<br>";
 }

this is the output.

com, net, edu, uk, au, in, biz, ca, cc, cd, bz, by <br>

(however, there are as many lines as there are array values)

I have tried using explode(), and it returns "array" with an error above it.

Upvotes: 0

Views: 373

Answers (4)

Nick
Nick

Reputation: 1412

Simply:

echo join('<br>', $domainext);

will do the job if you want each domain suffix separated with HTML line breaks (the exact required output is unclear from your question). Join is an alias of implode, and preferable from its clearer meaning.

Upvotes: 0

Robbert
Robbert

Reputation: 6582

If you just want to output the items in your array on a different row, you cna use join

echo join("<br/>",$domainext);

As others have said, no loop necessary.

Upvotes: 1

brechmos
brechmos

Reputation: 1316

I think this is what you are looking for:

$domainext = array("com","net","edu","uk","au","in","biz","ca","cc","cd","bz","by");

print implode("\n", $domainext);

This gives:

com
net
edu
....

Oops... replace the "\n" by a br tag if you are printing to a web page.

print implode("<br/>", $domainext);

Upvotes: 2

Azox
Azox

Reputation: 1940

You dont need to implode or explode anything :), try this:

foreach ($domainext as $ext){
        echo $ext."<br>";
        echo "<br>";
    }

Upvotes: 1

Related Questions