Create a comma-separated string from a single column of an array of objects
Better:
$resultstr = array();foreach ($results as $result) { $resultstr[] = $result->name;}echo implode(",",$resultstr);
1. Concat to string but add |
before
$s = '';foreach ($results as $result) { if ($s) $s .= '|'; $s .= $result->name; }echo $s;
2. Echo |
only if not last item
$s = '';$n = count($results);foreach ($results as $i => $result) { $s .= $result->name; if (($i+1) != $n) $s .= '|';}echo $s;
3. Load to array and then implode
$s = array();foreach ($results as $result) { $s[] = $result->name;}echo implode('|', $s);
4. Concat to string then cut last |
(or rtrim
it)
$s = '';foreach ($results as $result) { $s .= $result->name . '|';}echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';foreach($results as $result){ $result_names .= $result->name.',';}echo rtrim($result_names, ',');