Remove the last character from a string
PhpPhp 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.