Home > Software engineering >  How to remove the last comma of a Wordpress php foreach output?
How to remove the last comma of a Wordpress php foreach output?

Time:01-24

I already tried some things with trim and so on but nothing works.

Maybe I made a mistake and you can help me? The code looks currently like that:

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
    $output = '';
    foreach ($terms as $term) {
      $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a>, ';
    }
};
echo $output;

CodePudding user response:

Try putting in substr_replace($term->name,"",-1), check documentation for more info, this should delete comma from last string.

CodePudding user response:

just add a counter to check the last item of the array

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
    $output = '';
    $i = 0;
    foreach ($terms as $term) {
      $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a> ';

      $output .= ($i == count($terms) - 1) ? '' : ',';
      $i  ;
    }
};
echo $output;
  •  Tags:  
  • Related