Alternative 1
Add all values to an array and then just use implode() to glue them all together:
$catArray = [];
foreach((get_the_category()) as $category) {
$catArray[] = $category->cat_name;
}
// Now we can implode the array, using , as the glue
echo implode(', ', $catArray);
Alternative 2
You could also prepend the commas in your loop so you don't need any if-statements:
$glue = '';
foreach((get_the_category()) as $category) {
echo $glue . $category->cat_name;
$glue = ', ';
}
or a shorter version (not as readable though and requires PHP 7+):
foreach((get_the_category()) as $category) {
echo ($glue ?? '') . $category->cat_name;
$glue = ', ';
}
The first iteration won't get any comma in front of it, but the rest will.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…