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.

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

Thanks for ideas and help!

Upvotes: 1

Views: 2420

Answers (4)

Anoop Saini
Anoop Saini

Reputation: 307

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

Upvotes: 1

BVRoc
BVRoc

Reputation: 51

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;
?>

Upvotes: 3

lombervid
lombervid

Reputation: 156

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 ?>

Upvotes: 1

Matt S
Matt S

Reputation: 15364

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; ?>

Upvotes: 5

Related Questions