Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Linking items in a string - and removing trailing comma



10:39 pm on Nov 16, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

I can do either, but not both together, and there must be a way!

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?


11:25 pm on Nov 16, 2008 (gmt 0)

WebmasterWorld Senior Member dreamcatcher is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Hi abbeyvet,

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) ? ', ' : '');



12:16 am on Nov 17, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Thank you VERY much!

I used the first option, it works perfectly!


Featured Threads

Hot Threads This Week

Hot Threads This Month