Question

I have a set of tags that I stored in the database separated by spaces as a string. When I echo them out with php, I explode them and loop through them with a for loop.

My code looks something like this:

$tags = explode(' ',$c['art_tags']); for($i=0;$i<count($tags);$i++){ echo "<a href='#'>".$tags[$i]."</a>".", ";}

So far I've only seen posts with answers to use implode, but if I use implode, I wouldn't be able to click on the individual tags because it would be a string..

So I'm trying to figure out how to get rid of the last comma when I'm looping the tags array for each tag. It would ultimately appear like this:

<a href="">tag1</a>,<a href="">tag2</a>,<a href="#">tag3</a> 
Was it helpful?

Solution 2

You could just change the comma to the beginning of the echo in the for loop and implement a condition to check if its the first tag... like this:

<?php
$c='bob sally butch jim';

$tags = explode(' ',$c); 

for($i=0;$i<count($tags);$i++)
    { 
        if($i === 0)
            {
                echo "<a href='#'>" . $tags[$i] . "</a>";
            }

        else
            {
                echo ", <a href='#'>" . $tags[$i] . "</a>";
            }
    }
?>

OTHER TIPS

Use array_map() + implode():

<?php
$tags = explode(' ', $c['art_tags']);
$tags = array_map(function($tag){ return '<a href="#">' . $tag . '</a>'; }, $tags);

echo implode(', ', $tags);
?>

Working example @ PhpFiddle

You can use trim() or rtrim();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top