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?
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 (", ")
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