0

I am using this function:

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    foreach($terms as $term) {
        echo $term->name . ", ";
        unset($term);
    }
}

However I see the terms as term1, term2, term3, (with also a comma at the end), how can I show the terms with commas but without that comma when is not necessary?

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • Test for the end of the array. If you're not at the end, use the comma, otherwise, skip it. Here's an example that should be helpful. https://stackoverflow.com/questions/6092054/checking-during-array-iteration-if-the-current-element-is-the-last-element – Difster Jan 31 '18 at 20:00

4 Answers4

4

Instead of echoing all the variables during your loop, you should store them all to an array and then use the implode() function to echo them all with the formatting you desire.

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    $output = array();
    foreach($terms as $term) {
        $output[] = $term->name;
        unset($term);
    }
    echo implode(", ", $output)
}

Don't want to use an array or variable? There is another solution. Just check if you are currently on the very last element in the array during your loop.

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    end($terms);
    $endKey = key($terms);
    foreach($terms as $key => $term) {
        echo $key != $endKey? $term->name.", " : $term->name;
        unset($term);
    }
}

I added $key to the foreach loop so you can compare against that. You can get the final key of the array by doing end($array) and then using key() to get the actual key.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
0

If you dont want to use array use following:

$terms = get_the_terms($post->ID, 'skills');
$string = "";
if($terms != null) {
foreach($terms as $term) {
    $string .= $term->name . ", ";
    unset($term);
}
}

echo trim($string, ", ");
danny
  • 407
  • 1
  • 5
  • 10
0

You can use rtrim. (from php.net : Strip whitespace (or other characters) from the end of a string)

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    $stringFinal = "";
    foreach($terms as $term) {
        $stringFinal = $term->name . ", ";
    }
    $stringFinal = rtrim($stringFinal, ', ')
}
echo $stringFinal;
Davide
  • 566
  • 3
  • 13
0

Omitting all checks, this can be reduced to one line.

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');

echo implode(", ", array_map(function($T) {return is_a($T, 'WP_Term') ? $T->name : false; }, $terms ))

Works like array_column but with object

DocSS
  • 116
  • 4