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:
You’d use
rtrim()
Like this:
Example
you should try php’s inbuilt function.
it will minimize the code and also the precise way
thanks