2006
09.11
09.11
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.
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,’,')
You have a great blog here and it is Nice to read some well written posts that have some relevancy…keep up the good work
HI,
Thanks…… this what i want .
Hi Jon, your new preferred method work like a charm. short and sweet hahaha
Hi! I was surfing and found your blog post… nice! I love your blog.
Cheers! Sandra. R.
Quick & simple, thanks!
Muy bueno su blog me salvó el problema de eliminar la última coma. ¡Muchas Gracias!, sigan así
Fer
I created I dynamic query with checkboxes for the fields needed in the query. after removing the white space I needed something to remove the last comma in the string and that did it, cheers
thanks for good info. I prefer rtrim($str,’,’) because it’s safer.
thanks
There’s a better way to build that list. Use an array. ie –
$something = array();
$something[] = “item”;
$something[] = “item”;
$something[] = “item”;
$something[] = “item”;
implode( ‘,’ , $something);