Forum Moderators: coopster
I have created a tagging system, the tags are entered as a comma separated list, and I currently retrieve and display the tags like so:
$query = "SELECT pTags FROM tablename WHERE pID = whatever";
$result = mysql_query ($query);
$row = mysql_fetch_array($result);
$list = $row[0];
$tags = explode(',', $list);
foreach ($tags AS $tags)
{
echo "<a href=\"/tags.php?tag=$tags\">$tags</a>, ";
}
Which works fine, except of course I have a trailing comma and space.
I know I can print them out if I just needed the (unlinked) list using
$tags = substr($list, 0, -2);
echo $tags;
But how can I do both?
A couple of ways you can do this. Firstly, concatenate the vars and use substr_replace [us2.php.net]
$tagData = '';
foreach ($tags AS $tags)
{
$tagData .= "<a href=\"/tags.php?tag=$tags\">$tags</a>, ";
}
echo substr_replace($tagData, '', -2);
Or you can use a count to increment when looping and only add the comma if its not the last entry:
$count = 0;
foreach ($tags AS $tags)
{
echo "<a href=\"/tags.php?tag=$tags\">$tags</a>";
echo (++$count!=count($tags) ? ', ' : '');
}
dc