Jump to content

Stipping last comma


dk4210

Recommended Posts

Hello Guys,

 

I am trying to strip the last comma but I can't get it to work... Please advise

 

Here is my code, it adds the coma in between all numbers and on the end.

 

$query1 = mysql_query("SELECT b_id FROM benefits");
while ($row = mysql_fetch_array($query1)) {
$b_id = $row['b_id'];

$b_id . ",";

     echo $b_id2;

}

 

displays 1,2,3,4,5,6,7,8,9,10,

 

 

I also tried this but it didn't work. It removed all the commas

 


$query1 = mysql_query("SELECT b_id FROM benefits");
while ($row = mysql_fetch_array($query1)) {
$b_id = $row['b_id'];


$b_id . ",";
$b_id2 = rtrim($b_id,',');
     echo $b_id2;


}

 

 

Link to comment
Share on other sites

Can't think of anything else right now..

Hope this works..

 

<?php
$query1 = mysql_query("SELECT b_id FROM benefits");
$i = 1;
while ($row = mysql_fetch_array($query1)) {
     $count = mysql_num_rows($query1);

     if($i < $count){
     	echo $row['b_id'] . ",";
     }else{
echo $row['b_id'];
     }
     $i++;
}
?>

Link to comment
Share on other sites

The problem with your code is that you are doing everything within your while-loop. Focus the removal of the last coma outside your loop. There are 100s of different ways of doing what you're trying to achieve. One easy way is to just remove the last character of your string (since it's always a coma, right?). Try just doing it like this:

 

$query1 = mysql_query("SELECT b_id FROM benefits");
while ($row = mysql_fetch_array($query1)) {
$b_id .= $row['b_id'] . ",";
}
substr($b_id,0,-1);

 

That should remove the last coma, you can however do this in many other ways as I said earlier.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.