Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding Commas In an array

Status
Not open for further replies.

EvilAsh

Technical User
Oct 22, 2005
56
0
0
GB
This may be a bit of a no-brainer so my apologies in advance :)

I am trying to separate the items in a array with commas. Straight forward enough, except I am trying make it not have a comma on the last item.

To clarify, I am trying to do this:

item, item, item

but am getting

item, item, item,

The script I am using is:

Code:
while($i = mysql_fetch_array($result)) 
{

$subcategory=$i["subcategory"];
$string="";

for ($i=0; $i<count($subcategory); $i++)
    {
    $string.= $subcategory;
    if ($i == count($subcategory)-1)
        {
        $string.=", ";
        }
    else
        {
        $string.= "";
        }
    }
echo $string;
}

Now, this SHOULD work, but for the life of me, I cannot figure out why it doesn't.

I may not be seeing the would for the trees here. I would be grateful for any advice.

Thanks for reading.
 
It appears to me that $i is being used as an array element and a counter. Not sure if that could cause issues.

One thing I've done in this situation is

$j = 0;
while($i = mysql_fetch_array($result)){
if ($j = 0){
$string = $i["subcategory"];
}else{
$string .= ', ' . $i["subcategory"];
}
$j++;
}

Mark
 
Code:
while($i = mysql_fetch_array($result)) {
 $subcategory[]=$i["subcategory"];
}
echo implode(',', $subcategory);
}
 
I forgot about implode/explode and I use it all the time.

Mark
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top