How to remove last character from a string inside a loop
-
I am trying to print the different category's selected in a single line in xml, like <cat_name>meeting, food and drinks, sports</cat_name> The output I am getting: <cat_name>meeting, food and drinks, sports,</cat_name> I want to remove only the last comma. The code I have written so far is: $sq=" select category_main.cat_name from category_main join category on(category.cat_id=category_main.cat_id) where category.event_id='$event_id' "; $e=mysql_query($sq); $xml ='<cat_name>'; while($row=mysql_fetch_array($e)) { $res=$row['cat_name']; //$new = substr($val,0,-1); $xml .="$res, "; } $xml .='</cat_name>'; echo $xml;
-
Answer:
Call http://us.php.net/manual/function.trim.php with the optional second parameter as a ',' trim($cat_name, ',') However, since you're doing this in a while loop, you should build an array then implode() it rather than building the string in the loop. This avoids the extra comma to begin with. $arr = array(); while($row=mysql_fetch_array($e)) { $arr[] = $row['cat_name']; } $cat_name = implode(",", $arr); // $cat_name is now "meeting, food and drinks, sports"
nithin Kumar at Stack Overflow Visit the source
Other answers
You can do this by [i used my variable] $str = substr($str,0, (strlen($str)-1));
Sonal Khunt
Or use a rtrim, rtrim( $cat , ',' ) http://php.net/rtrim
Andrey Knupp
Related Q & A:
- How to replace a string inside of a Word Document?Best solution by Stack Overflow
- How to make parentheses bold in a string?Best solution by Stack Overflow
- How do I open a 'photo' inside a Yahoo email (rather than just attaching it?Best solution by uk.answers.yahoo.com
- How to remove a bed off a ford ranger?Best solution by wiki.answers.com
- How do you put a picture inside a picture frame of a picture using photoshop?Best solution by youtube.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.