How To Remove Last Comma From String Using PHP?

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

Useful Read : Export the MySQL database table as CSV format using PHP

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



Leave a Comment.