24

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.

My loop is just simple, as below

foreach($results as $result){
  echo $result->name.',';
}

Which echos out

result,result,result,result,

I just need to kill that pesky last comma.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Cecil
  • 1,609
  • 5
  • 21
  • 26

15 Answers15

116

Better:

$resultstr = array();
foreach ($results as $result) {
  $resultstr[] = $result->name;
}
echo implode(",",$resultstr);
Kiran Reddy
  • 734
  • 12
  • 28
LeleDumbo
  • 9,192
  • 4
  • 24
  • 38
30

1. Concat to string but add | before

$s = '';
foreach ($results as $result) { 
    if ($s) $s .= '|';
    $s .= $result->name; 
}
echo $s;

2. Echo | only if not last item

$s = '';
$n = count($results);
foreach ($results as $i => $result) { 
    $s .= $result->name;
    if (($i+1) != $n) $s .= '|';
}
echo $s;

3. Load to array and then implode

$s = array();
foreach ($results as $result) { 
    $s[] = $result->name;
}
echo implode('|', $s);

4. Concat to string then cut last | (or rtrim it)

$s = '';
foreach ($results as $result) { 
    $s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');

5. Concat string using array_map()

echo implode('|', array_map(function($result) { return $result->name; }, $results));
Glavić
  • 42,781
  • 13
  • 77
  • 107
14
$result_names = '';
foreach($results as $result){
    $result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
Mike
  • 4,839
  • 3
  • 25
  • 22
  • That would kill every comma in the loop wouldnt it? ... not just the one at the very end of the outputted string? – Cecil Jan 16 '11 at 14:22
  • 1
    I edited the snippet after I realized that you echoed from inside the loop. – Mike Jan 16 '11 at 14:24
2

I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.

I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.

$i=0;
foreach ($results as $result) {
    $i++;
    if(sizeof($results) > $i) {
        echo $result . ", ";
    } else {
        echo $result;
    }
}
jrgresh92
  • 29
  • 2
2

In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.

Code: (Demo)

$results = [
    (object)['name' => 'A'],
    (object)['name' => 'B'],
    (object)['name' => 'C']
];

echo implode(',', array_column($results, 'name'));

Output:

A,B,C

That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.


If you are processing a collection in Laravel, you can pluck() and implode():

$collection->pluck('name')->implode(',')
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
  $comma = ($i<$arraySize) ? ", " : "";
  echo $results[$i]->name.$comma;
}
Adam Ellis
  • 142
  • 13
0

Not as pretty, but also works:

$first=true;
foreach($results as $result){
    if(!$first) { echo ', '; }
    $first=false;
    echo $result->name;
}
Qiu
  • 5,651
  • 10
  • 49
  • 56
Alex Russell
  • 172
  • 1
  • 13
0

Another smart way is:

foreach($results as $result){
  echo ($passed ? ',' : '') . $result->name;
  $passed = true;
}

In this case at first loop $passed is NULL and , doesn't print.

Amir Fo
  • 5,163
  • 1
  • 43
  • 51
0

I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().

$array = array("A thing", "A whatsit", "eighty flange oscillators");
          
foreach( $array as $value ){
    echo $value;
    $nxt = next($array);
    if($nxt) echo ", "; // commas between each item in the list
    else echo ". And that's it."; // no comma after the last item.
}

// outputs: 
// A thing, A whatsit, eighty flange oscillators. And that's it.

play with it here

Alex Russell
  • 172
  • 1
  • 13
-1

I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:

foreach($arrayitem as $k){ $string =  $string.",".$k;
 } 

and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.

 echo substr($a,1,10000000);

hope this helps.

Binxalot
  • 41
  • 7
-1
$a[0] = 'John Doe';       
$a[1] = 'Jason statham';       
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
    $result .= $name;
    if($size > $key+1) $result .=', ';
}
echo $result;
kapa
  • 77,694
  • 21
  • 158
  • 175
  • What if the array is not numerically indexed? – kapa Sep 27 '12 at 11:16
  • It's a good idea to describe what you're doing, posting code only can be quite confusing. – Kao Sep 27 '12 at 11:20
  • 1
    Welcome to StackOverflow. Consider providing an explanation of any code you provide. This will allow the questioner to learn from your examples. Please see the FAQ on [writing good answers](http://meta.stackexchange.com/questions/7656/how-do-i-write-a-good-answer-to-a-question). – Joseph Mansfield Sep 27 '12 at 11:21
-1
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
    $str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
    if($len > $i)
    {
        $str .= ',';
        $i = $i+1;
    }
}
echo $str;
?>
Pang
  • 9,564
  • 146
  • 81
  • 122
shvmsngh99
  • 19
  • 1
  • 2
-1
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
    echo $result->name;
    if ( $i < $count ) echo ", ";                               
    ++$i;
}
?>
lky
  • 1,081
  • 3
  • 15
  • 31
-1

This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.

$i = 0;
$string = '';

foreach($array as $item){
    $string .= ($i++ ? ',' : '').$item;
}
lugreen
  • 102
  • 1
  • 8
-11

First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:

ob_start();
foreach($results as $result)
{
   echo $result->name.',';
}
$output = ob_get_clean();

echo rtrim($output, ',');

The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

shamittomar
  • 46,210
  • 12
  • 74
  • 78
  • 9
    There's no need for OB, just build a string, trim then echo. – BoltClock Jan 16 '11 at 14:22
  • 2
    @BoltClock: yes, but if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals. Thanks for +1. – shamittomar Jan 16 '11 at 14:24