Home >Backend Development >PHP Tutorial >How to Efficiently Create a Comma-Separated String from a Database Array Column?

How to Efficiently Create a Comma-Separated String from a Database Array Column?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 03:37:12583browse

How to Efficiently Create a Comma-Separated String from a Database Array Column?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn