819

What is fastest way to remove the last character from a string?

I have a string like

a,b,c,d,e,

I would like to remove the last ',' and get the remaining string back:

OUTPUT: a,b,c,d,e

What is the fastest way to do this?

11
  • 39
    if this string is concanating by a loop, you can use "implode" it will be concated without last comma Apr 8, 2011 at 9:24
  • 1
    @Tufan Barış Yıldırım: string concatenation is not in loop
    – I-M-JM
    Apr 8, 2011 at 9:34
  • 9
    Please don't worry about "fastest" without having first done some sort of measurement that it matters. Rather than worrying about fastest, think about which way is clearest. Sep 18, 2013 at 16:55
  • 5
    This should not be marked as a duplicate as the other question states that you know what the last character is ('a period').
    – FruitBreak
    Aug 5, 2014 at 16:04
  • 1
    @FruitBreak No its correctly marked as you can see by which answer I-M-JM accepted. It is again trim(). So he means "How to remove last specific characters from string?" and not "the last". All other answers are "wrong" by that. The only wrong duplicate marking has this question.
    – mgutt
    Apr 2, 2015 at 9:53

7 Answers 7

1316

Contrary to the question asked, rtrim() will remove any number of characters, listed in the second argument, from the end of the string. In case you expect just a single comma, the following code would do:

$newarraynama = rtrim($arraynama, ",");

But in my case I had 2 characters, a comma and a space, so I had to change to

$newarraynama = rtrim($arraynama, " ,");

and now it would remove all commas and spaces from the end of the string, returning a, b, c, d, e either from a, b, c, d, e,, a, b, c, d, e,,,, a, b, c, d, e, or a, b, c, d, e , ,, , ,

But in case there could be multiple commas but you need to remove only the last one, then rtrim() shouldn't be used at all - see other answers for the solution that directly answers the question.

However, rtrim() could be a good choice if you don't know whether the extra character could be present or not. Unlike substr-based solutions it will return a, b, c, d, e from a, b, c, d, e

11
  • 5
    How? Can you provide a kind of example
    – I-M-JM
    Apr 8, 2011 at 9:17
  • 4
    @I-M Just replace $string by your data, and echo the whole thing: echo rtrim("a,b,c,d,e,", ",");
    – anon
    Apr 8, 2011 at 9:18
  • 60
    Note that this does not answer the question as posted in the title.
    – DaveWalley
    Apr 11, 2014 at 16:39
  • thank you :) For More information please check TRIM & RTRIM & LTRIM Sep 5, 2014 at 9:27
  • 10
    Note that this is a dangerous way to remove the extra comma at the end of a CSV string (a quite common issue when concatenating values in a loop). This would indeed turn A;B;C;D; to A;B;C;D, but will also transform A;B;;; to A;B. Often one wants to preserve the delimiters between empty values, because a CSV parser could need to determine the number of fields from the string itself.
    – etuardu
    Jan 13, 2015 at 19:51
1100

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

This isolates the string from the start upto and including the second last character. In other words, it isolates the whole string except the last character.

In case the last character could be multi-byte, then mb_substr() should be used instead.

9
  • 33
    This is the good way. I wanted to remove last comma from a string like: "a,b,c,d,," and this is the correct solution because if you use rtrim() it will remove the two last comma.
    – serfer2
    Oct 15, 2013 at 8:24
  • This worked very well for me, very great method, had no idea you could use a negative number there and start from 0. I agree with the above comment, this is far better than rtrim, I had a similar issue where I didn't want to remove the last characters but a word from an SQL string at the END of the string only like " AND ", so I used this with substr("sqlstatement", 0, -7); to remove the last AND in the sequence of WHERE AND clauses I was writing. Worked like a charm :). Nov 8, 2013 at 7:49
  • If you know the number of characters that you want to remove, this is the better answer. solidlystated.com/scripting/…
    – ntrrobng
    Aug 26, 2014 at 5:22
  • 4
    trim and rtrim do not remove the last character in a string. Although sometimes that is all they do, they will often remove many characters from the string. e.g. rtrim('Assess','s') gives you 'Asse', not 'Asses'. That's why this answer is better than the accepted answer. Mar 20, 2015 at 4:52
  • 2
    The code is faulty, use this instead: $substring = substr($string, 0, strlen($string)-1); Jan 16, 2021 at 16:35
119

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

Note that this function is not multibyte-safe, and will produce the undesired result if the last character will happen to be a multi-byte one.

2
  • 4
    the problem with "so fast, it doesn't matter" is, that it may be in a loop. Imagine, that code is executed 50 times for every single letter in a long text. Suddenly every little bit of performance counts.
    – Till
    Jun 7, 2017 at 14:11
  • 1
    @Till I'm not sure if it works like that, I didn't check the source but I assume that substr_replace($str, $replacement, $start[, $length]) last couple of parameters limit the letters that are "surgically interventioned". I.e. substringing will only analyze/replace the substring's characters (in this case emptied). After this is done, the rest of the unaltered string is concatenated.
    – CPHPython
    Aug 9, 2018 at 10:03
18

You can use

substr(string $string, int $start, int[optional] $length=null);

See substr in the PHP documentation. It returns part of a string.

2
  • 1
    Sorry, but wasn't it the same answer given by @ashleedawg ? May 25, 2021 at 21:39
  • @SalustianoMuniz, no problem I think. The time difference between the answers is too short. Aug 2, 2022 at 10:23
5

Use the regular expression end of string anchor "$"

$string = preg_replace("/,$/", '', $string);
1
  • Surprisingly, I like this one for being meticulously correct: it will remove only a comma, only being the last character, and only if present Jun 20, 2022 at 15:15
1

if you do you really want to replace a last char:

$string = "a,b,c,d,e,";

$string[strlen($string)-1] = "";

echo $string; //output: a,b,c,d,e
1
  • this IMHO seems to be the fastest and least memory consuming solution?
    – medunes
    Mar 10 at 15:48
-1

"The fastest best code is the code that doesn't exist".

Speaking of edge cases, there is a quite common issue with the trailing comma that appears after the loop, like

$str = '';
foreach ($array as $value) {
    $str .= "$value,";
}

which, I suppose, also could be the case in the initial question. In this case, the fastest method definitely would be not to add the trailing comma at all:

$str = '';
foreach ($array as $value) {
    $str .= $str ? "," : "";
    $str .= $value;
}

here we are checking whether $str has any value already, and if so - adding a comma before the next item, thus having no extra commas in the result.

1
  • 1
    I love this answer, the solution does not remove the last character from a string YES. But based on the question trailing commas in a loop is most likely the reason you may want to remove the last character so why not use a better algorithm and you wont have to be worried about removing the last character Jun 19, 2022 at 11:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.