Friday 17 June 2016

How To Remove Last Comma From String Using PHP?

Generally, developers use loops to create a comma separated lists in stringformat. But, after the loop you end with a trailing comma at the end of the string.

To remove this comma we are going to use PHP’s built rtrim function. rtrim function is used to strip off whitespaces and predefined characters from right side of the string. It accepts two parameters,
  1. String – String we want to trim (Required)
  2. Character – Characters which we want to strip (Optional)
Here’s an example code:
$string = "a, b, c, d,";
$filtered = rtrim($string, ',');
echo $filtered;
As you can, we are passing a variable with a comma separated list and a comma(,) as second parameter. The output of above code is as follows.
a, b, c, d

0 comments:

Post a Comment