-1

How can I remove duplicate comma separated values returned from database?

I have it in this format:

XL,L,XXL
XL
M,L,XL
L,XL,M

What I tried:

$new_str = array_unique(array_map('trim', explode(',', $srow['size'])));
$string = implode(',', $new_str);

But I still get duplicate values. Is there a better way of doing it?

Nick
  • 138,499
  • 22
  • 57
  • 95
Fagbemi Ayodele
  • 321
  • 5
  • 15

1 Answers1

5

Since your data is stored as comma separated values in the database, you will need to aggregate all the values as you loop over fetching from the database and then remove duplicates e.g.

while ($srow = $result->fetch_assoc()) {
    $sizes[] = $srow['size'];
    // do other stuff with fetched data
    // ...
}
$sizes = array_unique(array_map('trim', explode(',', implode(',', $sizes))));
sort($sizes);
$string = implode(',', $sizes);

Demo on 3v4l.org (with simulated database fetch)

Nick
  • 138,499
  • 22
  • 57
  • 95