Create a comma-separated string from a single column of an array of objects

Cecil picture Cecil · Jan 16, 2011 · Viewed 45.1k times · Source

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.

Answer

LeleDumbo picture LeleDumbo · Jan 16, 2011

Better:

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