Optimal Telelicious Coding From AK To CT
 
« Creating and ISO image on a Mac in OSX
r.refine: A Scallable Raster-to-TIN Simplification »
 

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: ,

6 Responses to “Remove last comma of string in PHP”

  1.  
    Ross Patty
    November 10, 2006 | 12:23 am
     

    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.  
    Shaq
    December 14, 2006 | 4:59 pm
     

    Hi

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

    thanks

  3.  
    Haris N H
    January 8, 2007 | 3:12 am
     

    Thanks.This is very much useful to me

  4.  
    Alex Ezell
    February 21, 2007 | 5:50 pm
     

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

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

  5.  
    May 23, 2007 | 2:10 am
     

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

  6.  
    June 12, 2007 | 6:11 am
     

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

Leave a Reply