2006
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.

11 comments so far

Add Your Comment
  1. 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!

  2. Hi

    I wanted to know how can I implement this in to FOREACH statement

    thanks

  3. Thanks.This is very much useful to me

  4. This is covered in the PHP docs with this example:
    $rest = substr(“abcdef”, 0, -1); // returns “abcde”

    From: http://us3.php.net/substr

  5. It’s easier to make a list with join() or implode(). No ?

  6. I actually have a new preferred method for this: rtrim($str,’,')

  7. 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 ;)

  8. HI,

    Thanks…… this what i want .

  9. Hi Jon, your new preferred method work like a charm. short and sweet hahaha

  10. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  11. Quick & simple, thanks!