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>
Advertisement
Answer
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>"; } } ?>