Remove last comma of string in PHP
After building a list of items in a string (ie “x1,x2,x3,x4,”) I typically find myself needing to remove the last comma. After using this for the longest time:
$str = substr($str,0,strlen($str)-1);
I found:
$str = substr($str,'',-1);
This will actually remove the last character whatever it is so be careful, for my uses it’s perfect.
I know this is not novel but it’s elegant and these are the things that make my day.
Tags: Computers, Web Development
This was exactly what I was looking for. I find it nearly impossible to locate PHP functions when I know what I want to do but not what it’s called, and this saved me a lot of trouble. Thanks!
Hi
I wanted to know how can I implement this in to FOREACH statement
thanks
Thanks.This is very much useful to me
This is covered in the PHP docs with this example: $rest = substr(”abcdef”, 0, -1); // returns “abcde”
From: http://us3.php.net/substr
It’s easier to make a list with join() or implode(). No ?
I actually have a new preferred method for this: rtrim($str,’,')