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
Release: 2024-12-15 03:37:12
Original
583 people have browsed it

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.',';
}
Copy after login

This code will output:

result,result,result,result,
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template