Home >Backend Development >PHP Tutorial >How to Avoid Trailing Commas When Creating Comma-Separated Strings from Object Arrays?

How to Avoid Trailing Commas When Creating Comma-Separated Strings from Object Arrays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 08:42:07567browse

How to Avoid Trailing Commas When Creating Comma-Separated Strings from Object Arrays?

Generating Comma-Separated Strings from Object Array Columns

When working with databases and arrays of objects, it becomes necessary to generate comma-separated strings from specific columns. One common issue is having an extraneous comma after the last value.

To address this, a preferred method is to create a new array. For each object in the original array, extract the desired value and store it in the new array. This approach ensures that the last element will not have a trailing comma.

Here's an improved code snippet:

$resultstr = array();
foreach ($results as $result) {
  $resultstr[] = $result->name;
}
echo implode(",", $resultstr);

The above is the detailed content of How to Avoid Trailing Commas When Creating Comma-Separated Strings from Object Arrays?. 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