How can I add a comma to this list?

Viewed 42

In the code below, I need to put a comma at the end of the author names.

foreach($terms as $term){
echo  '<a href="'.esc_url(get_term_link( $term, 'product_author' )).'">'.esc_html($term->name).'</a>';
            }

Example: A, B, C
Note: 1. A comma is not required if the author is one.
2. There is no need for a comma after the last author's name.

1 Answers

In PHP this is usually achieved by imploding an array. Given an array like this:

$array = ['David', 'Charles', 'Peter', 'John'];

Doing this implode:

$result = implode(', ', $array);

Would give you this string:

David, Charles, Peter, John

See: implode().

You can do the same with your links like this:

$links = [];
foreach ($terms as $term) {
     $links[]  = '<a href="' . 
                 esc_url(get_term_link($term, 'product_author')) .
                 '">' .
                 esc_html($term->name) .
                 '</a>';
}
echo implode(', ', $links);
Related