Removing last comma in array when looping without turning it into a string


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> 


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:

$c='bob sally butch jim';

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

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

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

Answered By – rmorr

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published