Making Lists Easier and More Beautiful
A common challenge: how to create a neat listing like a, b, c, d without trailing commas or awkward spacing.
The Verbose Way
The typical approach uses a flag to track the first iteration:
$first = true;
foreach ($array as $value) {
if ($first) {
$first = false;
} else {
$out .= ', ';
}
$out .= $value;
}
It works, but it’s clunky. Every loop iteration runs a conditional that’s only meaningful once.
The Clean Way
Use implode():
$out = implode(', ', $array);
Done. No flags, no conditionals.
When You Need Formatting
If each item needs transformation—like wrapping in HTML links—build a prepared array first, then implode:
$temp = [];
foreach ($array as $value) {
$temp[] = '<a href="/' . $value . '/">' . $value . '</a>';
}
$out = implode(', ', $temp);
Or with array_map:
$out = implode(', ', array_map(function($value) {
return '<a href="/' . $value . '/">' . $value . '</a>';
}, $array));
The Principle
Separate data preparation from string concatenation. The result is much more comfortable and much more readable code with fewer checks and cleaner logic flow.
Simple problems deserve simple solutions.