791

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
I-M-JM
  • 15,192
  • 26
  • 75
  • 103
  • 38
    if this string is concanating by a loop, you can use "implode" it will be concated without last comma – Tufan Barış Yıldırım Apr 08 '11 at 09:24
  • 1
    @Tufan Barış Yıldırım: string concatenation is not in loop – I-M-JM Apr 08 '11 at 09: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. – Andy Lester Sep 18 '13 at 16:55
  • Or you can find the fastest and add a comment, then you get speed, clarity and no worries. – DaveWalley Apr 11 '14 at 16:33
  • 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 05 '14 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](http://stackoverflow.com/q/6636491/318765). – mgutt Apr 02 '15 at 09:53
  • It would be appreciated IF when marking a string as duplicate - you added a link to where the answer is that this thread is a duplicate of. – Chezshire Jun 12 '15 at 18:13
  • Related http://stackoverflow.com/questions/31632379/how-can-i-remove-a-character-at-position – Gottlieb Notschnabel Jul 26 '15 at 00:52
  • This doesn't seem to be a duplicate. The suggested dupe-target is about *conditionally* removing characters (the title and accepted answer indicate that *multiple* characters may be removed); this is about unconditionally removing a single character, and adds the aspect of *performance*. – Kyle Strand Sep 27 '18 at 12:19
  • The "dupe" asks "*How to remove all specific characters at the end of a string?*" which is not the same as "*Remove the last character from string*". Although similar, this question is different. Voting to reopen. – Eaten by a Grue Apr 25 '19 at 02:16

5 Answers5

1284

First, I try without a space, rtrim($arraynama, ","); and get an error result.

Then I add a space and get a good result:

$newarraynama = rtrim($arraynama, ", ");
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • 5
    How? Can you provide a kind of example – I-M-JM Apr 08 '11 at 09:17
  • 4
    @I-M Just replace `$string` by your data, and echo the whole thing: `echo rtrim("a,b,c,d,e,", ",");` –  Apr 08 '11 at 09:18
  • 1
    really great!, at least for me... i am too searching for this..and found it here... thanks +1 – Mohammed Sufian Jan 24 '14 at 21:45
  • 60
    Note that this does not answer the question as posted in the title. – DaveWalley Apr 11 '14 at 16:39
  • thank you :) For More information please check [TRIM](http://php.net/manual/en/function.trim.php) & [RTRIM](http://php.net/manual/en/function.rtrim.php) & [LTRIM](http://php.net/manual/en/function.ltrim.php) – Rahul Mandaliya Sep 05 '14 at 09:27
  • A pity that there is no possibility for limiting the amount. If you think so too vote here: https://bugs.php.net/bug.php?id=49007 – Wilt Sep 12 '14 at 12:05
  • Of all the great answers supplied, this is the most elegant, since if for some reason the last character is not a comma it will not delete it. I learned from the other answers that substr and substr_replace take negative values. I had to look it up. thanks to all – sdfor Oct 27 '14 at 19:50
  • 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 '15 at 19:51
  • Hi, I know this post was already old but how about if the string `a,b,c,d & e` was in a while loop that retrieved from a `database`? I mean something like this: `while($rows = mysql_fetch_assoc($query)){ $letters = $rows['letters']; $let = "$letters,"; echo rtrim($let, ","); }` – Archie Zineg Feb 11 '15 at 04:16
  • It's worth noticing that `rtrim` isn't limited to single characters, it can remove a trailing chain if asked (e.g. `rtrim($string, "
    ")`).
    – Skippy le Grand Gourou Aug 08 '15 at 15:41
  • trim would also delete any commas at the start – J3STER Mar 07 '18 at 04:24
  • WOW, that space makes a big difference... if you find out that doing it without a space doesn't work :P – samjco Dec 16 '20 at 00:28
1074

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Nicola Peluchetti
  • 74,514
  • 30
  • 136
  • 188
  • 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 '13 at 08: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 :). – Joseph Astrahan Nov 08 '13 at 07:49
  • 37
    This should be the accepted answer - it removes last character (not just ',') as was originally asked. – DaveWalley Apr 11 '14 at 16:41
  • Agreed @DaveWalley this is the best answer as the original question does not imply you know what the last character is! – FruitBreak Aug 05 '14 at 16:01
  • If you know the number of characters that you want to remove, this is the better answer. http://solidlystated.com/scripting/php-best-way-to-remove-last-character/ – ntrrobng Aug 26 '14 at 05: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. – Buttle Butkus Mar 20 '15 at 04:52
  • tried this script, and i think it works way better in the sense that removes the trailing character, being a comma or another weird ASCII thing.... – Pablo Contreras Dec 03 '15 at 17:59
  • Although Anon's answer works exactly as expected and desired for any MySQL query using lists, Nicola's answer properly answers the question as asked as well as drops any undesired last character. – Bad_Neighbor Feb 16 '17 at 04:12
  • easy to understand – Shady Mohamed Sherif Feb 24 '17 at 17:11
  • This works thanks (: – Walk Jun 06 '17 at 05:08
  • As question was about string and for string substr works better than rtrim so this answer should be accepted instead. – Imran Qamer Oct 02 '17 at 11:14
  • I think this is a correct answer given the question title, it is "remove the last character from string" not "the last comma" – Pedro Emilio Borrego Rached Jun 06 '18 at 18:50
  • substr($string,0,-1); – Võ Minh Nov 28 '18 at 07:35
  • 2
    The code is faulty, use this instead: `$substring = substr($string, 0, strlen($string)-1);` – Unterbelichtet Jan 16 '21 at 16:35
  • I agree, should this not be `strlen($string)-1` instead of -1 ? – Adam Jul 12 '21 at 12:45
120

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.

ashleedawg
  • 18,752
  • 7
  • 68
  • 96
bart
  • 7,434
  • 3
  • 32
  • 39
  • 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 07 '17 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])`](http://php.net/manual/en/function.substr-replace.php) last couple of parameters limit the letters that are "surgically interventioned". I.e. _[`substr`](http://php.net/manual/en/function.substr.php)inging_ 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 09 '18 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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Bas van Ommen
  • 1,183
  • 2
  • 11
  • 19
-2

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

Your Common Sense
  • 154,967
  • 38
  • 205
  • 325