How to remove the last character in a string in PHP ?
How to remove the last character in a string in PHP ?
You have a string, let’s say “1,2,3,4,5,6,7,8,” that is generated in a loop, and you want to remove the last comma that is occurred on the last position of the string, to obtain a string like this: “1,2,3,4,5,6,7,8”.
1st solution
1 2 3 |
$string = "1,2,3,4,5,6,7,8,"; $newString = rtrim($string, ","); echo $newString; //outputs "1,2,3,4,5,6,7,8" as a string |
Note: “rtrim” function would cut trailing commas.
1 2 3 |
$string = "1,2,3,4,5,6,7,8,"; $newString = trim($string, ","); echo $newString; //outputs "1,2,3,4,5,6,7,8" as a string |
Note: “trim” function would cut trailing and prefixing commas.
2nd solution
1 2 |
$newString = substr("1,2,3,4,5,6,7,8,", 0, -1); echo $newString; //outputs "1,2,3,4,5,6,7,8" as a string |
The above one is a more “minified” version, and if you simply want the last comma to be eliminated, and you want performance, this is the one that should be used.