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.

1
  • 3
    $string = rtrim($string, ','); Commented Nov 18, 2014 at 0:39

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

0

This should work for you:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.