Search code examples
phparrayscsvresultsetarray-column

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


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.


Solution

  • 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.