Add comma in foreach loop php

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.

Add comma in foreach loop php

mickmackusa

39k11 gold badges76 silver badges112 bronze badges

asked Jan 16, 2011 at 14:15

0

Better:

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

Add comma in foreach loop php

answered Jan 16, 2011 at 14:23

LeleDumboLeleDumbo

9,1024 gold badges23 silver badges38 bronze badges

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));

answered Oct 26, 2014 at 13:03

GlavićGlavić

41.7k13 gold badges74 silver badges107 bronze badges

1

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

answered Jan 16, 2011 at 14:17

MikeMike

4,7693 gold badges24 silver badges22 bronze badges

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;
    }
}

answered Jul 14, 2018 at 1:02

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(',')

answered Sep 13, 2020 at 2:50

Add comma in foreach loop php

mickmackusamickmackusa

39k11 gold badges76 silver badges112 bronze badges

$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
  $comma = ($i<$arraySize) ? ", " : "";
  echo $results[$i]->name.$comma;
}

answered May 29, 2012 at 3:05

Not as pretty, but also works:

$first=true;
foreach($results as $result){
    if(!$first) { echo ', '; }
    $first=false;
    echo $result->name;
}

Add comma in foreach loop php

Qiu

5,49110 gold badges49 silver badges56 bronze badges

answered Aug 18, 2015 at 19:01

Add comma in foreach loop php

1

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.

answered Feb 24, 2018 at 16:30

Amir FoAmir Fo

4,4061 gold badge39 silver badges45 bronze badges

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

answered Feb 15, 2021 at 16:57

Add comma in foreach loop php

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.

answered May 13, 2012 at 15:44

$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

76.2k20 gold badges156 silver badges174 bronze badges

answered Sep 27, 2012 at 11:06

3

$value)
{
    $str .= ''.$value['cat_title'].'';
    if($len > $i)
    {
        $str .= ',';
        $i = $i+1;
    }
}
echo $str;
?>

Add comma in foreach loop php

Pang

9,193146 gold badges85 silver badges118 bronze badges

answered Apr 24, 2017 at 9:49

shvmsngh99shvmsngh99

191 silver badge2 bronze badges

name;
    if ( $i < $count ) echo ", ";                               
    ++$i;
}
?>

answered Oct 5, 2018 at 10:38

heady12heady12

9513 gold badges12 silver badges25 bronze badges

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;
}

answered Aug 26, 2020 at 11:19

lugreenlugreen

921 silver badge8 bronze badges

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.

answered Jan 16, 2011 at 14:21

shamittomarshamittomar

45.4k12 gold badges73 silver badges78 bronze badges

2

How do you put a comma in a foreach loop?

If your intention is to show comma after each element except the last one, you can easily use $loop->last() inside your foreach.

How do you remove the last comma in a for loop?

An alternative method of removing the comma from last foreach loop item. In this alternative way, we are going to use the PHP array_push() function. below is the code: