Implode within for each loop

I am trying to add a comma and space to each tag (except the last) within a foreach loop. I have been reading up on implode() but can’t make it work as intended

     <?php foreach($tags as $tag): ?>
        <a class="h2" href="/work/category:<?= $tag ?>">
        <?= implode(',', $tag) ?>
        </a>
    <?php endforeach ?>

You have to use implode() after linking and putting it into the new array first.

<?php 
    $tagsArray = [];
    foreach($tags as $tag)
        $tagsArray[] = '<a class="h2" href="/work/category:' . $tag . '">' . $tag . '</a>';
    
    echo implode(", ", $tagsArray);
?>
2 Likes

Perfect! Thank you so much. I have been going through your code and it all makes sense to me except I haven’t seen the use of these dots before . $tag . would you be able to explain?

The dot and quote used to concatenate text with variables in PHP (When we want to concatenate the PHP tag without closing it). For more information, you can review the document and the comments below: https://www.php.net/manual/en/language.operators.string.php

1 Like

On a side note: When mixing HTML and PHP in templates etc., such string concatenation should generally be avoided, but in examples like the above, its perfectly fine

1 Like

Would you suggest another method?

No, not at all! There is no other way here.

The only alternative to the foreach loop would be an array_map, but you would still need the string concatenation for the link.