WordPress PHP如果不等于,但如果大于


WordPress PHP if not equal to but if greater than

我有一个WordPress网站,我试图使用PHP动态创建一个逗号分隔的值列表。然而,我所有的列表末尾都有一个逗号,而我似乎不知道如何删除它。

我当前的代码是;

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

末尾有一个逗号,应该是空白的。我尝试了以下代码,但没有成功;

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

有人知道我做错了什么吗?

只需修剪最后一个逗号:

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

您应该使用rtrim()

像这样:

rtrim($string, ',');

Example

您应该尝试php的内置函数。

它将最小化代码以及的精确方式

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

感谢