5

I have this code that should display a list of values from an array followed by a comma and space! However I don't want the last one to have a comma and space after it.

So for example I want tag1, tag2, tag3 instead of tag1, tag2, tag3,

This is my code:

<?php $terms = get_the_terms( $the_post->ID, 'posts_tags' );
                                foreach ( $terms as $term ) {

                                    echo $term->name;echo ", ";
                                } ?>
3
  • 2
    You've asked this before.. stackoverflow.com/questions/5358001/wordpress-echo-out-array Commented Mar 23, 2011 at 15:15
  • Different question! I'm asking how to remove the last comma! Commented Mar 23, 2011 at 15:17
  • 1
    but the answer is still implode. check @rocket's answer for instance Commented Mar 23, 2011 at 15:19

2 Answers 2

26
$output = array();
foreach($terms as $term){
  $output[] = $term->name;
}
echo implode(', ', $output);
Sign up to request clarification or add additional context in comments.

2 Comments

Makes me wonder why a language as php and a framework like wordpress do not have any decent library to do even the most basic operations. Rails -> array.join(", ")
@Marek: It does. implode(', ', $array).
1

It´s an build in php feature called implode -> http://php.net/manual/function.implode.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.