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
https://forums.phpfreaks.com/topic/235422-stipping-last-comma/
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
https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209879
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
https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209881
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.