Search code examples
phptrim

PHP trim end comma from string


I have a simple PHP loop that iterates over a column in my table of trainers.

The data that it is getting is their first and last name. I am trying to remove the ending comma in the string once there are no more results in the iteration but it does not seem to work.

// Get the trainers
foreach ($data->trainers as $trainers) {
  $trainer .= (string)$trainers->trainer->trainerFirst. ' ' . (string)$trainers->trainer->trainerLast.',';
}
// Trim the trailing comma
rtrim($trainer, ",");

I would have expected this to work but the output is always First Last, instead of First Last.

Any ideas on what I am doing wrong?


Solution

  • rtrim doesn't modify the string in place, it returns a new string, so you need to assign the return value. Try this:

    // Trim the trailing comma
    $trainer = rtrim($trainer, ",");