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,eWhat is the fastest way to do this?
105 Answers
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, ", "); 13 You can use substr:
echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e' 15 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.
2You can use
substr(string $string, int $start, int[optional] $length=null);See substr in the PHP documentation. It returns part of a string.
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.