Coder Perfect

What is the best way to delete a comma at the end of a string?


I’d like to get rid of the comma at the end of a string. Right now, I’m utilizing

$string = substr($string,0,-1);

However, this merely removes the string’s last character. Because I’m inserting the string dynamically, there may be no comma at the end of the string at times. How can I get PHP to delete the comma from the end of the string if one is present?

Asked by zeckdude

Solution #1

$string = rtrim($string, ',');

Rtrim documents can be found here.

Answered by Sigurd

Solution #2

This is a classic problem with two answers. If you want to get rid of one comma that might or might not be there, type:

if (substr($string, -1, 1) == ',')
  $string = substr($string, 0, -1);

Use the simpler: if you wish to remove all commas from the end of a line.

$string = rtrim($string, ',');

The rtrim function (and its left trim counterpart, ltrim) is quite handy since it allows you to define a range of characters to remove, for example, to remove commas and following whitespace, write:

$string = rtrim($string, ", \t\n");

Answered by Ben Russell

Solution #3

i guess you’re concatenating something in the loop, like

foreach($a as $b)
  $string .= $b . ',';

It’s far better to collect items in an array and then join them with the delimiter you require.

foreach($a as $b)
  $result[] = $b;

$result = implode(',', $result);

This eliminates the difficulties of trailing and duplicate delimiters that are common in concatenation.

Answered by user187291

Solution #4

You may also do it this way if you’re concatenating stuff in the loop:

$coma = "";
foreach($a as $b){
    $string .= $coma.$b;
    $coma = ",";

Answered by cesar.mi

Solution #5

Take a look at the rtrim command.

rtrim ($string , ",");

If the last character is a comma, the above line will remove a char.

Answered by Anand Shah

Post is based on