Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 667
Cecil Avatar asked Jan 16 '11 14:01

Cecil


People also ask

How do you make a comma-separated string from an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you add comma separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you get a comma-separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.

How do you add comma separated values in a string array in Java?

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.


1 Answers

Better:

$resultstr = array(); foreach ($results as $result) {   $resultstr[] = $result->name; } echo implode(",",$resultstr); 
like image 74
LeleDumbo Avatar answered Sep 26 '22 21:09

LeleDumbo