Advertisement
Advertisement


Remove the last character from a string


Question

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?

2019/09/29
1
718
9/29/2019 5:34:46 PM

Accepted Answer

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, ", ");
2019/09/29
1212
9/29/2019 5:42:38 PM


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.

2018/11/29

You can use

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

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

2019/09/29

Source: https://stackoverflow.com/questions/5592994
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]