0

I'm storing some data in a "specialties" column of a MySQL db like so:

,,specialty1,,,,specialty2,,,,specialty3,

First, I take that data and turn it into an array:

$specialties = $location['specialties'];
$specialties_array = sw::shared()->users->unserializeArray($specialties);
foreach ($specialties_array as $specialty) {
    $specialty = str_replace(',', '', $specialty);
    echo $specialty . ", "; 
}

unSerializeArray function:

public function unserializeArray($string) {

    $array = explode(",,",$string);
    unset($array[0]);
    $array = array_values($array);

    return $array;

}

My problem with the function above is some of the array values still have a single comma attached to them after that function runs.

So next I use str_replace to remove commas to ensure the specialty value is separated. After separating the specialty value I then re-add a single comma to each specialty for output.

Ideally, I would like to show the specialties without a comma after the last specialty:

specialty1, specialty2, specialty3

However, it is outputting like this of course:

specialty1, specialty2, specialty3,

How can I remove the last comma when I am echoing each specialty separately rather than an array as a whole? Is there a better way to do this?

I tried the solution from this thread: Removing last comma from a foreach loop but I think the way I'm storing the data (,,specialty1,,,,specialty2,,,,specialty3,) is causing an issue with this solution.

Community
  • 1
  • 1
cpcdev
  • 1,130
  • 3
  • 18
  • 45

2 Answers2

1

Explode on a single comma, use array_filter to remove empty entries, and implode to rejoin the values:

public function unserializeArray($string) {
    return array_values(array_filter(explode(',' $string)));
}
...
echo implode(',',$sw::shared()->users->unserializeArray($specialties));
Steve
  • 20,703
  • 5
  • 41
  • 67
0

This should work for you:

$str= rtrim($str, ',');
Rizier123
  • 58,877
  • 16
  • 101
  • 156