remove last comma from string

rgb192
rgb192 used Ask the Experts™
on
I have a forloop that adds a $var and , to $string

how to remove last comma


example

3,4,5,6,2,
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
$string = rtrim($string, ",");

Open in new window

Most Valuable Expert 2011
Top Expert 2016
Commented:
The advantage of using rtrim() is that if you have empty positions at the end of the array and wind up with something like this 3,4,5,,, it will declop all of the commas at the end.  Thus it is better than something like substr($str,0,-1).

But I have another suggestion for you.  Why use an iterator at all?  Why not do something like this...

$arr = array(3,4,5,6,2);
$str = implode(',', $arr);

HTH, ~Ray

Author

Commented:
thanks both delete the last ,

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial