Remove comma on last item of foreach

I have next code for WordPress loop of tags for single post:

<?php if ($tags) : foreach($tags as $tag): ?>
<a href="<?php echo get_tag_link($tag); ?>">
    <?php echo $tag->name; ?>
</a>, 
<?php endforeach; endif; ?>

I have comma added to last anchor. There is also white space after comma.

Read More

How can I remove the comma from last anchor while I am doing this with foreach() PHP loop?

Thanks for ideas and help!

Related posts

4 comments

  1. Check if your loop is working on the last one:

    <?php if ($tags) : ?>
        <?php $count = count($tags); ?>
        <?php foreach($tags as $i => $tag): ?> 
            <a href="<?php echo get_tag_link($tag); ?>">
                <?php echo $tag->name; ?>
            </a>
            <?php if ($i < $count - 1) echo ", "; ?>
        <?php endforeach; ?>
    <?php endif; ?>
    
  2. What has a higher cost, calling a function or setting a variable? Here’s another way to do it perhaps, which sets a variable and removes the offending chars at the end – no extra math or if checks needed.

    <?php
      $tagoutput = '';
      if ($tags) {    
        foreach ($tags as $tag)
          $tagoutput .= '<a href="' . get_tag_link($tag) . '">' . $tag->name . '</a>, ';
        $tagoutput = rtrim($tagoutput, ', ');
      }
      echo $tagoutput;
    ?>
    
  3. You can do it the other way around (remove it from the first one). If your array is numeric you can try something like this:

    <?php if ($tags): ?>
        <?php foreach ($tags as $key => $tag): ?>
            <?php if ($key > 0): ?>,<?php endif ?>
            <a href="<?php echo get_tag_link($tag); ?>">
                <?php echo $tag->name; ?>
            </a>
        <?php endforeach ?>
    <?php endif ?>
    
  4. You can also try it using counter.

    $values = array('value','value','value');
            $count = count($values);
            $i = 0;
            foreach($values as $value){
                $i++;
                echo $value;
            if($count > $i){
                echo ', ';
            }
        }
    

    Output: value, value, value

Comments are closed.