1

I have a WordPress site where I am trying to dynamically create a comma separated list of values using PHP. However all of my lists have a comma at the end when they shouldn't and I can't seem to work out how to remove it.

My current code is;

$tcount=count($terms);
foreach($terms as $term){
    echo $term->name;
    if($tcount>1){
        echo ', ';
    }
}

There is a comma at the end where it should simply be blank. I tried the following code instead but it didn't work;

$tcount=count($terms);
foreach($terms as $term){
    echo $term->name;
    if(!$tcount==$tcount && $tcount>1){
        echo ', ';
    }
}

Does anyone know what I'm doing wrong?

3 Answers 3

2

Just trim the last comma:

$result = "";

$tcount=count($terms);
foreach($terms as $term) {
  // save output in temporary variable...
  $result .= $term->name;
  $result .= ', ';
}
echo substr($result, 0, -2);  // delete last two characters (", ")
Sign up to request clarification or add additional context in comments.

Comments

0

You'd use rtrim()

Like this:

rtrim($string, ',');

Example

2 Comments

rtrim() for sure looks cleaner than my approach (substr()), but it won't work for OP's output string, take a look here. It should be rtrim($string, ', '), with space added. However, this will trim also last name, if it ends with comma - although this is unlikely, it's a little hidden side-effect that may be difficult to spot.
@MichałRybak good spot, I was going to go with the substr() way but thought OP wanted quick and clean, thank you for pointing out the rest!
0

you should try php's inbuilt function.

it will minimize the code and also the precise way

$output = array();
foreach($terms as $term){
  $output[] = $term->name;
}
echo implode(', ', $output);

thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.