Remove last character from string in PHP

E-mail
Written by Henrik, Tuesday, 24 February 2009 Last Updated ( Wednesday, 11 March 2009 17:26 )

After looking around for a way to actually remove the last character of my string even if it was not the last one in the string given, I came up with these two ways. I figure that the one using strrev() is a lot faster then the one using explode(), but as someone might want the first way, I publish it anyway.

This was the way I had done to remove the last character of any given string:

$str = substr($str,0,strlen($str)-1);

This was the second thing I tried (SLOWER)

$string = "adml,madadsdsadsadasdsa,    asd";
$string = explode(",", $string);
array_pop($string);
$string = implode(",", $string);
// Will output: adml,madadsdsadsadasdsa
echo $string;

This is probably one of the better way of doing it! (FASTER)

$string = "adml,madadsdsadsadasdsa,    asd";
$string = strrev($string);
$string substr($string,strpos($string,",")+1);
// Will output: adml,madadsdsadsadasdsa
echo strrev($string);

Like this Joomla template?

As many other things on this site it is completely free! In collaboration with Midsjö AB are we releasing it into the public domain under the GNU/GPL version 2 license. You will find this template and other extensions under the Labs section then Joomla!. Good luck and happy Joomling!