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: 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.
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 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.
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.
Better:
$resultstr = array(); foreach ($results as $result) { $resultstr[] = $result->name; } echo implode(",",$resultstr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With