$string = rtrim($string, ',');
Docs for rtrim
here
This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:
if (substr($string, -1, 1) == ',')
{
$string = substr($string, 0, -1);
}
If you want to remove all commas from the end of a line use the simpler:
$string = rtrim($string, ',');
The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:
$string = rtrim($string, ", \t\n");
i guess you're concatenating something in the loop, like
foreach($a as $b)
$string .= $b . ',';
much better is to collect items in an array and then join it with a delimiter you need
foreach($a as $b)
$result[] = $b;
$result = implode(',', $result);
this solves trailing and double delimiter problems that usually occur with concatenation
If you're concatenating something in the loop, you can do it in this way too:
$coma = "";
foreach($a as $b){
$string .= $coma.$b;
$coma = ",";
}
have a look at the rtrim function
rtrim ($string , ",");
the above line will remove a char if the last char is a comma
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With