Creating a Comma-Separated String from an Array Column
An array of objects can be converted into a comma-separated string. For instance, when exporting data from a database, one may want to strip the final comma from the resulting string.
Consider a simple foreach loop that echoes values from a database:
foreach($results as $result){ echo $result->name.','; }
This code will output:
result,result,result,result,
To remove the last comma, an improved approach is to utilize an array and implode it afterwards:
$resultstr = array(); foreach ($results as $result) { $resultstr[] = $result->name; } echo implode(",",$resultstr);
This revised code eliminates the unnecessary comma at the end.
The above is the detailed content of How to Efficiently Create a Comma-Separated String from a Database Array Column?. For more information, please follow other related articles on the PHP Chinese website!