Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

php - Add comma after value only if more than one value?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...