Page 1 of 1

Seperating by commas?

Posted: Thu Aug 14, 2003 6:10 pm
by Mr. Tech
Hi!

I have created a links directory script. On the main categories I am wanting to show 4 sub categories. E.G:

Main Category
This is the description...
Sub Cat 1, Sub Cat2, Sub Cat 3, Sub Cat 4 ...


All this information of the categories are stored in a mysql database.

What I need help with is getting the commas in between the sub cats... I could just use this:

Code: Select all

<?php
$subcats .= "<a href="cat.php?cat=$cat">$catname</a>, ";
?>
But on the last sub category(Sub Cat 4) it will put a comma on the end which I dont want...

How would I get commas on only the first 3 and not the forth?

Thanks

Posted: Thu Aug 14, 2003 8:21 pm
by Drachlen

Code: Select all

<?php
mysql_connect("localhost", "name", "pass") or die("Could not connect"); 
mysql_select_db("database") or die("Could not select database");
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
for($a=0;$a<$rows;$a++){
if($a == $rows-1){
$c = "";
}
if($a != $rows-1){
$c = ", ";
}
echo "<a href=cat.php?cat=a>a</a>$c";
}
?>
This is what I came up with. Tested and whatnot. Reply if you have a problem.

Posted: Thu Aug 14, 2003 10:31 pm
by qartis
It's faster to do:

Code: Select all

$array = ("Home","News","About","Email","Downloads","Links");
unset ($i);
foreach ($array as $number => $text){
if (!empty($i)){
echo ", ";
}
echo "<a href=index.php?cat={$number}>{$text}</a><br />\r\n";
$i=1;
}

Posted: Fri Aug 15, 2003 12:39 am
by Mr. Tech
Thanks guys! I'll give it a try!

Posted: Fri Aug 15, 2003 1:01 am
by Mr. Tech
Drachlen's worked best. Thanks anyway qartis. ;)