Remove the last character from a string

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?

10

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

2

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like