3

Heres what i mean:

foreach ($array as $a) {
 echo $a.',<br/>';
}

current output would be:

a,
a,
a,
a,

i want the output to be like this:

a,
a,
a,
a

(all 'a' separated with comma and when it comes to the last loop it doesnt write a comma)

2
  • 1
    use echo implode(",<br />",$array) Commented Mar 28, 2013 at 21:25
  • Do you also want the <br/> but no comma? Commented Mar 28, 2013 at 21:26

6 Answers 6

11

Try this:

echo implode(",<br/>", $array);
Sign up to request clarification or add additional context in comments.

Comments

3

If the length of array is too large or you have multidimensional array use the below code

<?php $len=count($array);
    foreach($array as $a){ 
        echo $a; 
        if( $len > 1) echo ','; 
        $len--;
 } ?>

Comments

2

If you'd also like to convert any newlines in the array to <br />, which might be ideal if you're outputting:

echo nl2br(implode(',' . PHP_EOL, $array));

4 Comments

why the trim() and the nl2br, instead of directly imploding with <br/>?
nl2br because I like it to look nice in the source code as well -- I don't know why I had trim. Also, it would convert any new lines in the array, which you might want.
@MichaelRushton: That does not "look nice" but adds heavy load AND BUGs. If he had line-breaks in the values of $array they are now pretty much converted to <br>s, so your code is not working identical to the original code of the question. (Though I admit you might be right about what he intended to code.)
I should probably add a note to clarify the assumption I made.
1

PHP has the implode function for that:

 implode(",<br>", $array);

Comments

1

Nobody said you can make it this way:

foreach($array as $element) { 
    $separator = ($element != end($array)) ? ",<br />" : '';
// or $separator = ($element == end($array)) ? '' : ",<br />";   
    echo $element.$separator;
}

I suppose this is going to output exactly what you wish.

Comments

0

You should use implode except for one situation.

If the output is huge, and you don't want to keep it in memory before sending to the output (e.g. itemwise processing) then you should do something like:

$remain=count($array);
foreach ($array as $a) {
    echo $a;
    if($remain-->0) echo ',';
    echo '<br/>';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.