Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Im trying to echo a set of values for categories. What I'd like to do is if there are more than one value, append a comma afterwards. Here's a snippet of what I have:

<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ', '; } ?>

The problem with this is that categories with one value will have a comma at the end.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...