dk4210 Posted May 3, 2011 Share Posted May 3, 2011 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; } Quote Link to comment https://forums.phpfreaks.com/topic/235422-stipping-last-comma/ Share on other sites More sharing options...
fugix Posted May 3, 2011 Share Posted May 3, 2011 so what exactly are you trying to accomplish? Quote Link to comment https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209876 Share on other sites More sharing options...
kney Posted May 3, 2011 Share Posted May 3, 2011 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++; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209879 Share on other sites More sharing options...
Undrium Posted May 3, 2011 Share Posted May 3, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209881 Share on other sites More sharing options...
dk4210 Posted May 3, 2011 Author Share Posted May 3, 2011 That worked perfect kney.. Thanks every one for your help! Quote Link to comment https://forums.phpfreaks.com/topic/235422-stipping-last-comma/#findComment-1209891 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.