Remove the last character from a string

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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, ", ");

Solution 2 - Php

You can use substr:

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

Solution 3 - Php

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.

Solution 4 - Php

You can use

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

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

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionI-M-JMView Question on Stackoverflow
Solution 1 - PhpanonView Answer on Stackoverflow
Solution 2 - PhpNicola PeluchettiView Answer on Stackoverflow
Solution 3 - PhpbartView Answer on Stackoverflow
Solution 4 - PhpBas van OmmenView Answer on Stackoverflow
Solution 5 - PhpYour Common SenseView Answer on Stackoverflow