php – Remove duplicate comma separated values from mysql-ThrowExceptions

Exception or error:

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

I have it in this format:


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?

How to solve:

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))));
$string = implode(',', $sizes);

Demo on (with simulated database fetch)

Leave a Reply

Your email address will not be published. Required fields are marked *