Fritex Fritex - 7 months ago 9
PHP Question

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!

Answer

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