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.

Short URL:

20 thoughts on “Remove last comma of string in PHP”

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

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

  4. ^ Assuming it’s a server side generated list.. List could be a from a $_POST.

    I had to swap out ” for 0 in the second parameter. ” threw a warning.

  5. Hi,
    Here i want to mentioned that sometimes this below code wont work:
    substr(“abcdef”, 0, -1);
    because it has space at last of the string so instead used this one:
    substr(trim(“abcdef ”), 0, -1);

    hope help for anyone
    Saleha A.Latif

Leave a Reply

Your email address will not be published. Required fields are marked *